我有一个数据框foo
,其中包含4个空列,我需要填充列表result
的内容。我不能通过公共ID进行合并,因为其中一个不存在,但foo
和result
长度相同。如何访问result
的每个元素的内容并将其转换为数据帧foo
的列?
我理解要访问单个列表元素的每个部分,必须写:result[[1]][1]
,result[[1]][2]
,result[[1]][3]
,result[[1]][4]
,但是如何迭代他们?
我试过了
for (i in 1:length(result)){
foo$coords.x1.min <- result[[i]][1]
}
但这仅使用列表中的第一个值填充整个列
> nrow(foo)
[1] 103
> length(result)
[1] 103
> head(foo)
names X1 X2 X3 X4
1 4CITIES NA NA NA NA
2 ACES NA NA NA NA
3 ADVANCES NA NA NA NA
4 AMASE NA NA NA NA
5 ARCHMAT NA NA NA NA
6 ASC NA NA NA NA
> head(result)
[[1]]
min max
coords.x1 -3.7038 16.3738
coords.x2 5.6761 50.8503
[[2]]
min max
coords.x1 -5.4710 25.1442
coords.x2 35.3387 56.4152
[[3]]
min max
coords.x1 -9.1393 21.0122
coords.x2 38.7223 57.0488
[[4]]
min max
coords.x1 2.1734 22.1567
coords.x2 41.3851 65.5848
[[5]]
min max
coords.x1 -7.9093 22.9444
coords.x2 38.5707 41.9028
[[6]]
min max
coords.x1 3.0573 24.9384
coords.x2 44.4949 60.1699
答案 0 :(得分:0)
这是一个解决方案
for (i in 1:length(result)){
foo$X1[i] <- result[[i]][1]
foo$X2[i] <- result[[i]][2]
foo$X3[i] <- result[[i]][3]
foo$X4[i] <- result[[i]][4]
}
答案 1 :(得分:0)
我们可以通过unlist
'结果'在没有循环的情况下执行此操作,将其转换为包含4列的matrix
,并将其分配给'foo'列,但第一列除外一个
foo[-1] <- matrix(unlist(result), ncol=4, byrow = TRUE)
foo
# names X1 X2 X3 X4
#1 4CITIES -3.7038 5.6761 16.3738 50.8503
#2 ACES -5.4710 35.3387 25.1442 56.4152
#3 ADVANCES -9.1393 38.7223 21.0122 57.0488
#4 AMASE 2.1734 41.3851 22.1567 65.5848
#5 ARCHMAT -7.9093 38.5707 22.9444 41.9028
#6 ASC 3.0573 44.4949 24.9384 60.1699
result <- list(structure(c(-3.7038, 5.6761, 16.3738, 50.8503), .Dim = c(2L,
2L), .Dimnames = list(c("coords.x1", "coords.x2"), c("min", "max"
))), structure(c(-5.471, 35.3387, 25.1442, 56.4152), .Dim = c(2L,
2L), .Dimnames = list(c("coords.x1", "coords.x2"), c("min", "max"
))), structure(c(-9.1393, 38.7223, 21.0122, 57.0488), .Dim = c(2L,
2L), .Dimnames = list(c("coords.x1", "coords.x2"), c("min", "max"
))), structure(c(2.1734, 41.3851, 22.1567, 65.5848), .Dim = c(2L,
2L), .Dimnames = list(c("coords.x1", "coords.x2"), c("min", "max"
))), structure(c(-7.9093, 38.5707, 22.9444, 41.9028), .Dim = c(2L,
2L), .Dimnames = list(c("coords.x1", "coords.x2"), c("min", "max"
))), structure(c(3.0573, 44.4949, 24.9384, 60.1699), .Dim = c(2L,
2L), .Dimnames = list(c("coords.x1", "coords.x2"), c("min", "max"
))))
foo <- structure(list(names = c("4CITIES", "ACES", "ADVANCES", "AMASE",
"ARCHMAT", "ASC"), X1 = c(NA, NA, NA, NA, NA, NA), X2 = c(NA,
NA, NA, NA, NA, NA), X3 = c(NA, NA, NA, NA, NA, NA), X4 = c(NA,
NA, NA, NA, NA, NA)), .Names = c("names", "X1", "X2", "X3", "X4"
), class = "data.frame", row.names = c("1", "2", "3", "4", "5",
"6"))