如何在类似数据库的结构中正确声明和填充列(当从一列的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]]

  • 现在,我如何在循环之前,正确地声明一些新列,并将它们的类型声明为ISODate(例如)。受访者人数为整数

    我习惯于使用数据库。所以我只想说ALTERTABLE,添加数据类型为Date的列

    在R怎么做

  • 此外,如何将每个测量的长度不同的子结构放入测量对象中(人员-具有子字段,如名字和姓氏)

    在一个数据库中,我将创建一个带有调查ID和参与者ID的单独链接表,以及一个带有参与者ID和列First\u name和Last\u name的另一个表

    但是在R中是否有一种优雅的方法可以做到这一点(例如,data_frame column Participant是某种更深层次的结构?我是否必须停止使用data.frame并将调查转换为列表

  • 这里有一个方法:

    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-好吧,我会像在数据库中一样将人员放在单独的表中。