【发布时间】:2014-02-10 16:22:07
【问题描述】:
R 的菜鸟在这里。试图弄清楚一些事情。我需要构建一个将新列添加到数据集开头的函数。这个新列是用户指定的其他列中的值的串联。
假设这是名为 myDataSet 的数据集:
col_1 col_2 col_3 col_4
bat red 1 a
cow orange 2 b
dog green 3 c
用户可以这样使用函数:
addPrimaryKey(myDataSet, cols=c(1,3,4))
要获得一个新数据集的结果,其中第 1、3 和 4 列连接成一个名为 ID 的列并添加到开头,如下所示:
ID col_1 col_2 col_3 col_4
bat1a bat red 1 a
cow2b cow orange 2 b
dog4c dog green 3 c
这是我一直在写的剧本,但我已经盯着它看了这么久,我想我犯了一些错误。我不知道如何正确地将参数中的列号获取到粘贴函数中。
addPrimaryKey <- function(df, cols=NULL){
newVector = rep(NA, length(cols)) ##initialize vector to length of columns
colsN <- as.numeric(cols)
df <- cbind(ID=paste(
for(i in 1:length(colsN)){
holder <- df[colsN[i]]
holder
}
, sep=""), df) ##concatenate the selected columns and add as ID column to df
df
}
任何帮助将不胜感激。非常感谢
【问题讨论】: