如果这是基本问题,请道歉。我是新手。任何方向都非常感谢。
我的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对应于col中“m”之后的数字。名称和Var2对应于名称中“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回应好像表达式不完整(+)。 这是一个语法错误的问题吗?或者我需要另一个解决方案来填充新列? 提前谢谢。
答案 0 :(得分:1)
你可以试试这个:
数据:
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