如何在类似数据库的结构中正确声明和填充列(当从一列的data.frame开始时)
我不是新手,也不是职业选手。 我不能很好地解决这个问题 假设此结构: 调查是具有以下结构的数据框架如何在类似数据库的结构中正确声明和填充列(当从一列的data.frame开始时),r,dataframe,R,Dataframe,我不是新手,也不是职业选手。 我不能很好地解决这个问题 假设此结构: 调查是具有以下结构的数据框架 surveys=data.frame(id=c(1L,3L,5L)) surveys 有3个调查ID,但假设我有一个2000多个调查的长列表 还有一个网站可以给我一个XML,里面有关于调查的更多信息。 例如,有多少人参与,何时完成。 整个结构如下所示: survey -1 survey_id -2 number of respondents -3 names of respondents -
surveys=data.frame(id=c(1L,3L,5L))
surveys
有3个调查ID,但假设我有一个2000多个调查的长列表
还有一个网站可以给我一个XML,里面有关于调查的更多信息。
例如,有多少人参与,何时完成。
整个结构如下所示:
survey
-1 survey_id
-2 number of respondents
-3 names of respondents - (each respondent has a first name and last name)
-4 when_done
-5 when_received
我想向调查“data.frame”或(或列表列表)添加行和维度
这将是web服务调用的结果
所以我做了一个这样的循环
for (1:nrow(surveys))
{
current=surveys$id[i]
webout=getWebServiceResults(current)
this will outputs a list of variables such as when_done, when_received)
and now I want to store results of the webservice calls into the surveys structure by adding correct rows to surveys)
}
假设webservice输出是list,我可以使用webout[[5]]
surveys<- data.frame(id=c(1L,3L,5L))
# Dummy, but returns a list with elements of correct types
getWebServiceResults <- function(id) list(id=id, foo=sample(letters,1), bar=runif(1))
set.seed(42)
r <- lapply(surveys$id, getWebServiceResults)
# r is now a list where each element is a row
# Create a 0-row data.frame with the correct column names and types
d <- data.frame(id=integer(), foo=character(), bar=numeric(), stringsAsFactors=FALSE)
# Finally call rbind with the empty data.frame and all the rows...
d <- do.call(rbind, c(list(d), r))
d
# id foo bar
#2 1 x 0.9370754
#21 3 h 0.8304476
#3 5 q 0.5190959
surveysthx。这很好地解决了问题#1.那么#2.如何存储调查中的人员姓名。可以像第一步一样使用列表(创建变量r)。我认为data.frame的目标结构不适合解决第二个问题。@user984532-好吧,我会像在数据库中一样将人员放在单独的表中。