将列表转换为R中具有特定列名称的数据框 [英] converting list to data frame with specific column names in R
问题描述
我已经查看了此处的其他类似主题,但尚未找到我的问题的答案.我在for循环中构建了一个列表,希望将其转换为数据框.最终列表如下所示:
I've reviewed the other similar threads on here but haven't found the answer to my question yet. I'm building a list in a for loop that I want to convert to a data frame. The final list looks like this:
[[1]]
[1] 117
[[2]]
[1] 1041
[[3]]
[1] 243
[[4]]
[1] 474
[[5]]
[1] 402
我想将其转换为具有特定列名称的数据框:ID和Nob.因此,例如,对于数据帧中的第5行,ID的行值将为5,而鲍勃的值将为402.运行此代码:
I want to convert this to a data frame, with specific column names: ID and nobs. So for example for 5th row in the data frame, the row value for ID would be 5 and the value for bobs would be 402. Running this code:
d <- data.frame(cbind(l))
给我列,但没有名称.如何以及在哪里可以指定列名?我只是在学习R.谢谢您的帮助.
gives me the columns but without the names. How and where can I specify the column names? I am just learning R. Thanks for any help.
这是我的功能的完整代码:
this is the full code for my function:
complete <- function(directory, id) {
files_full <- list.files(directory, full.names = TRUE)
l <- list()
for (i in id){
nobs <- sum(complete.cases(read.csv(files_full[i])))
l[i] <- nobs
}
d <- data.frame(cbind(l))
d
}
推荐答案
您可以尝试以下操作:
l <- list(a=305,b=354,c=436,d=36)
> l
$a
[1] 305
$b
[1] 354
$c
[1] 436
$d
[1] 36
data.frame(id=names(l), nobs=unlist(l))
id nobs
a a 305
b b 354
c c 436
d d 36
data.frame(l)
a b c d
1 305 354 436 36
unlist(l)
a b c d
305 354 436 36
请注意,第一个和第二个是data.frame的,而最后一个是数字矢量.
Note that first and second are data.frame's, but last is named numeric vector.
列表中可能没有您的姓名,例如您的示例. 我假设您要创建命名列表并将其转换为data.frame ... 如果要在列表中设置名称,则应该可以:
Probably you don't have any names in your list as in your example. I presume that you want to create named list and convert it to data.frame... If you want to set names to your list it should work:
complete <- function(directory, id) {
files_full <- list.files(directory, full.names = TRUE)
l <- vector(mode='list', length=length(files_full))
for (i in files_full){
nobs <- sum(complete.cases(read.csv(i)))
l[i] <- nobs
}
d <- data.frame(cbind(l))
d
}
但是让我们尝试一下:
sapply(list.files(), function(x)sum(complete.cases(read.csv(x))))
它应该返回如下内容:
But let's try this:
sapply(list.files(), function(x)sum(complete.cases(read.csv(x))))
It should return something like:
a.csv b.csv c.csv
2153 326 235
这篇关于将列表转换为R中具有特定列名称的数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!