我正在尝试通过 for 循环创建一个数据框,并尝试为数据框的每一行添加一个向量。
行是人,列是名称类别和点类别。
例如,我正在尝试使用类似...
Name Points
Susie c(12,45,23)
Bill c(13,24,12,89)
CJ c(12)
Run Code Online (Sandbox Code Playgroud)
到目前为止我的代码看起来像
names_list <-c("Susie","Bill","CJ")
result = data.frame()
for (name in names_list){
listing = .....
frame = data.frame(name,listing)
names(frame) = c("name","list")
result <- rbind(result,frame)
}
Run Code Online (Sandbox Code Playgroud)
列表恰好是与该名称相关联的点。但是,它不是为包含所有点的每个名称创建 1 行,而是为每个点创建具有相同名称的多行。
结果看起来像
1 Susie 12
2 Susie 45
3 Susie 23
4 Bill 13
5 Bill 24
6 Bill 12
7 Bill 89
8 CJ 12
Run Code Online (Sandbox Code Playgroud)
The specific problem you've encountered is due to data.frame flattening any list inputs. This can be prevented using the identify function I. For example,
data.frame(a = 1, b = list(c("a", "b")))
Run Code Online (Sandbox Code Playgroud)
doesn't do what you want, but
data.frame(a = 1, b = I(list(c("a", "b"))))
Run Code Online (Sandbox Code Playgroud)
does. A discussion of this behavior and some alternatives are available at http://r4ds.had.co.nz/many-models.html#list-columns-1
You can use I to produce the desired result using your example as well:
names_list <-c("Susie","Bill","CJ")
points <- list(c(12,45,23),
c(13,24,12,89),
12)
result = data.frame()
for (i in 1:length(names_list)){
frame = data.frame(names_list[[i]], I(points[i]))
names(frame) = c("name","list")
result <- rbind(result,frame)
}
Run Code Online (Sandbox Code Playgroud)
though as pointed out in the comments, there are better ways to do it. All you really need is
data.frame(
name = names_list,
points = I(points))
Run Code Online (Sandbox Code Playgroud)
我不知道你的向量值在什么结构中,但一般来说,要将向量嵌套在一列中,你可以这样做:
names <- c("A", "B", "C")
vectors <- list(list(1,2,3), list(4,5,6), list(7,8,9))
as.data.frame(cbind(names, vectors))
names vectors
1 A 1, 2, 3
2 B 4, 5, 6
3 C 7, 8, 9
Run Code Online (Sandbox Code Playgroud)