2016-10-20 3 views
0

Rでデータをインポートしたときに結合された列があります 列にはc(-122.430061, 37.785553)のようなデータがあります。これを2列に分割するにはどうすればいいですかlonglat分割された(x、y)座標はRで結合されました

データは次のようになります。

#dput(coords[1:5,]) 
structure(list(type = c("Point", "Point", "Point", "Point", "Point" 
), coordinates = list(c(-122.191986, 37.752671), c(-122.20254, 
37.777845), c(-122.250701, 37.827707), c(-122.270252, 37.806838 
), c(-122.259369, 37.809819))), .Names = c("type", "coordinates" 
), row.names = c(1L, 2L, 3L, 5L, 6L), class = "data.frame") 
+0

申し訳ありません、多分私の質問は本当に明確です。上記の文字列は2ではなく1列にあるため、データフレームには2つの列があります。x [1] = point x [2] = c(-122.430061,37.785553) –

+0

データはすでにURLからjsonとしてインポートされています。したがって、scanはdata.frameでは機能しません。 –

+0

'cbind(df [" type "]、do.call(rbind、df $ coordinates))'を実行し、名前を設定することができます。 –

答えて

2

さて、あなたのデータを見た後、これは行くための正しい方法だ:

x <- structure(list(type = c("Point", "Point", "Point", "Point", "Point" 
), coordinates = list(c(-122.191986, 37.752671), c(-122.20254, 
37.777845), c(-122.250701, 37.827707), c(-122.270252, 37.806838 
), c(-122.259369, 37.809819))), .Names = c("type", "coordinates" 
), row.names = c(1L, 2L, 3L, 5L, 6L), class = "data.frame") 

x$coordinatesは、文字列の列が、リストではありません。

我々は "["sapplyを使用することができます
#[[1]] 
#[1] -122.19199 37.75267 
# 
#[[2]] 
#[1] -122.20254 37.77784 
# 
#[[3]] 
#[1] -122.25070 37.82771 
# 
#[[4]] 
#[1] -122.27025 37.80684 
# 
#[[5]] 
#[1] -122.25937 37.80982 

long <- sapply(x$coordinates, "[", 1) 
# [1] -122.1920 -122.2025 -122.2507 -122.2703 -122.2594 

lat <- sapply(x$coordinates, "[", 2) 
# [1] 37.75267 37.77784 37.82771 37.80684 37.80982 

しかし、もっと効率的な方法以下の私の元の答えに使用するトリックを経由している:私は、これはあなたが探しているものを、おそらくだと思う

xx <- unlist(x$coordinates) 

long <- xx[seq(1,length(xx),2)] 
# [1] -122.1920 -122.2025 -122.2507 -122.2703 -122.2594 

lat <- xx[-seq(1,length(xx),2)] 
# [1] 37.75267 37.77784 37.82771 37.80684 37.80982 

オリジナル回答

あなたがキャラクター列を持っていると仮定すると(現時点ではファクターであれば、最初に強制的にas.characterを使います):

## example column 
x <- c("12.3, 15.2", "9.2,11.1", "13.7,22.5") 
#[1] "12.3, 15.2" "9.2,11.1" "13.7,22.5" 

xx <- scan(text = x, what = numeric(), sep = ",") 
#[1] 12.3 15.2 9.2 11.1 13.7 22.5 

long <- xx[seq(1,length(xx),2)] 
#[1] 12.3 9.2 13.7 

lat <- xx[-seq(1,length(xx),2)] 
#[1] 15.2 11.1 22.5 
1

インポートを再実行したくない場合。 library(tidyr)は、クリーンアップが少しグロスです。このseperate()

datf <- tidyr::separate(datf, coordinates, into = c("long", "lat"), sep = ",") 
datf$long <- gsub("c\\(", "", datf$long) 
datf$lat <- gsub("\\)", "", datf$lat) 

gsub()のための素晴らしい機能を持っていますが、それは仕事を取得します。誰かが私のseparateコールで改善できるかもしれません。

関連する問題