在 R 中创建和填充数据框中的列

create and fill columns in dataframe in R

如果这是基本问题,我们深表歉意。我是新手。非常感谢任何指示。

我有如下 df1 (POSIXct)(135 行)

> head(df1)
    uniqueSessionsIni   uniqueSessionsEnd
1 2015-01-05 15:00:00 2015-01-05 15:59:00
2 2015-01-05 15:00:00 2015-01-05 15:59:00
3 2015-01-05 15:00:00 2015-01-05 15:59:00

向量名称 - 新的 600 列的名称,如下所示。

> head(names)
[1] "m0p0" "m1p0" "m2p0" "m3p0" "m4p0" "m5p0"...

> head(allPairs)
  Var1 Var2 names
1    1    0  m1p0
2    1    1  m1p1

我想用基于以下内容的值填充 df1 的所有行,第 4 列到第 603 列:矢量名称 - 使用新的 600 列的名称,如下所示。 uniqueSessionsIni Var1 + Var2.
您会注意到 Var1 对应于列中 "m" 之后的数字。 names,var2对应names中"p"后的数字

结果会是这样的(但有更多的列)。

> head(df1)
    uniqueSessionsIni   uniqueSessionsEnd           m1p0                 m1p1    
1 2015-01-05 15:00:00 2015-01-05 15:59:00   2015-01-05 15:01:00  2015-01-05 15:02:00
2 2015-01-05 16:00:00 2015-01-05 15:59:00   2015-01-05 16:01:00  2015-01-05 16:02:00
3 2015-01-05 17:00:00 2015-01-05 15:59:00   2015-01-05 17:01:00  2015-01-05 17:02:00

我已尝试使用以下代码在 df1 中创建新列:

df1[,names] <- NA  

这成功创建了新列并填充了 NA

所以我尝试创建一个带有 for 循环的条件来填充这些新列(3 到 603),代码为

df1[,names] <- for (i in df1$timestamps)
df1$uniqueSessionsIni + (as.posix(allPairs$Var1) + (as.posix(allPairs$Var2)

但是 R 的响应好像表达式不完整 (+)。 这是语法错误的问题吗?或者我需要另一种解决方案来填充新列?
提前谢谢你。

你可以试试这个:

数据:

df1 <- data.frame(uniqueSessionsIni=as.POSIXlt(c('2015-01-05 15:00:00','2015-01-05 16:00:00', '2015-01-05 17:00:00 ')),
                  uniqueSessionsIni=as.POSIXlt(c('2015-01-05 15:59:00','2015-01-05 16:59:00', '2015-01-05 17:59:00 ')))

#note that the names column below should be of character class and not factor
allPairs <- data.frame(Var1=c(1,1), Var2=c(0,1), names=c('m1p0','m1p1'),stringsAsFactors=F)

解决方案:

#the list below creates the columns you need
mylist <- list()
for (i in 1:nrow(allPairs)){
  mylist[[allPairs[i, 3]]] <- df1$uniqueSessionsIni + 60*as.numeric(allPairs[i, 1]) + 60*as.numeric(allPairs[i, 2])
}

> mylist
$m1p0
[1] "2015-01-05 15:01:00 GMT" "2015-01-05 16:01:00 GMT" "2015-01-05 17:01:00 GMT"

$m1p1
[1] "2015-01-05 15:02:00 GMT" "2015-01-05 16:02:00 GMT" "2015-01-05 17:02:00 GMT"
#cbind all df1 and the new column from the loop
cbind(df1, data.frame(mylist))

输出:

> cbind(df1, data.frame(mylist))
    uniqueSessionsIni uniqueSessionsIni.1                m1p0                m1p1
1 2015-01-05 15:00:00 2015-01-05 15:59:00 2015-01-05 15:01:00 2015-01-05 15:02:00
2 2015-01-05 16:00:00 2015-01-05 16:59:00 2015-01-05 16:01:00 2015-01-05 16:02:00
3 2015-01-05 17:00:00 2015-01-05 17:59:00 2015-01-05 17:01:00 2015-01-05 17:02:00