在for循环中连接列

时间:2017-12-04 04:34:40

标签: r loops for-loop concatenation

我有一个样本数据框coords,其中包含一对坐标和一个`id:

> coords
  coords.x1 coords.x2  id
1 -77.06983  38.89720   A
2 -77.02854  38.89055   B
3 -77.04489  38.88567   C

我的目标是遍历数据框中的每一行,连接每一行的坐标,然后打印出每行的id。结果应该是这样的:

[1] "-77.06983,  38.89720"
[1] "A" 

[2] "-77.02854,  38.89055"
[2] "B" 

[3] "-77.04489,  38.88567"
[3] "C" 

但是下面的代码产生了不同的东西:

for (i in coords) {

  print(coords[i, c("coords.x1", "coords.x2")])

  print(coords[i, "id"])

} 


  coords.x1 coords.x2
1 -77.06983  38.89720
2 -77.02854  38.89055
3 -77.04489  38.88567
[1] "A" "B" "C"
     coords.x1 coords.x2
NA          NA        NA
NA.1        NA        NA
NA.2        NA        NA
[1] NA NA NA
     coords.x1 coords.x2
NA          NA        NA
NA.1        NA        NA
NA.2        NA        NA
[1] NA NA NA

为什么会发生这种情况,我在这个for循环中在语法上做错了什么?任何建议将不胜感激

以下是示例数据:

> dput(coords)
structure(list(coords.x1 = c(-77.06983, -77.028545, -77.0448866666667
), coords.x2 = c(38.897195, 38.8905533333333, 38.8856716666667
), id = c("A", "B", "C")), .Names = c("coords.x1", "coords.x2", 
"id"), row.names = c(NA, -3L), class = "data.frame")

1 个答案:

答案 0 :(得分:0)

您需要更改为

for (i in 1:nrow(coords)) {
.
.
.
}

并尝试避免for循环,如果可能的话,因为它们在R中非常慢 从purrr尝试类似map()的函数或者应用像lapply sapply和stuff这样的familiy函数。

print_coords = function(i,x){
  print( x[i,c("coords.x1", "coords.x2")])
  print(x[i,"id"])
}

invisible(lapply(1:nrow(coords),print_coords,x = coords))