![](/img/trans.png)
[英]How to fill in the columns of R dataframe with the corresponding column names as values
[英]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对应于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的响应好像表达式是不完整的(+)。 这是语法错误吗? 还是我需要另一个解决方案来完全填充新列?
先感谢您。
您可以尝试以下方法:
数据:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.