编写一个函数,该函数与“;单独的;R中的dplyr函数
我正在做一个练习来练习写作功能。问题是要求我的函数再现与编写一个函数,该函数与“;单独的;R中的dplyr函数,r,function,dplyr,R,Function,Dplyr,我正在做一个练习来练习写作功能。问题是要求我的函数再现与dplyr中的separate函数相同的输出 我有以下数据框: df <- data.frame(dates = c("2005-06-29", "2005-07-16", "2005-12-01"), values = c("F:62:130", "F:68:149", "M:68:160"), stringsAsFactors = FALSE) 我遇到的问
dplyr
中的separate
函数相同的输出
我有以下数据框:
df <- data.frame(dates = c("2005-06-29", "2005-07-16", "2005-12-01"),
values = c("F:62:130", "F:68:149", "M:68:160"),
stringsAsFactors = FALSE)
我遇到的问题是在函数中命名新列。这就是我到目前为止所做的:
into <- c()
names(into) <- c(a = "", b = "", c = "")
如何在函数中创建一个
到
参数,让我根据需要命名列?这里是一个基本的R解决方案
dfout <- cbind(df,`colnames<-`(do.call(rbind,strsplit(df$values,":")),c("a","b","wt")))
在
base R
中,我们可以使用substring
transform(df, a = substr(values, 1, 1),
b = substring(values, 3, 4),
wt = substring(values, 6))
或者另一个更简单的选择是使用
read.table
读取,将sep
指定为:
,并通过赋值或cbind
在原始数据集上创建列
df[c('a', 'b', 'wt')] <- read.table(text = df$values, sep=":", header = FALSE)
df
# dates values a b wt
#1 2005-06-29 F:62:130 F 62 130
#2 2005-07-16 F:68:149 F 68 149
#3 2005-12-01 M:68:160 M 68 160
df[c('a','b','wt')]我想这个错误来自我在函数中的一个注释。换了@akrun是否可以选择删除带有cbind
的列?例如,我想在最终输出中删除“values”列,它是函数中的colnum
参数。我尝试了cbind(df[,-colnum],setNames(list(a,b,c),into))
@user12310746基于您展示的示例,它正在为me@user12310746这里,colnum
已经更新。请早些时候查看我的评论。此外,这也行不通,相反,如果您有一个列名称或编号存储为v1,那么您将输出[[j1]]@user12310746
> dfout
dates values a b wt
1 2005-06-29 F:62:130 F 62 130
2 2005-07-16 F:68:149 F 68 149
3 2005-12-01 M:68:160 M 68 160
transform(df, a = substr(values, 1, 1),
b = substring(values, 3, 4),
wt = substring(values, 6))
df[c('a', 'b', 'wt')] <- read.table(text = df$values, sep=":", header = FALSE)
df
# dates values a b wt
#1 2005-06-29 F:62:130 F 62 130
#2 2005-07-16 F:68:149 F 68 149
#3 2005-12-01 M:68:160 M 68 160
myfunc <- function(df, colnum = 2, into = c("a", "b", "c"), sep = ":") {
# Use "colnum" to access the specified column of "df"
j1 <- colnum
colnum <- df[ , colnum]
# Split "df" using the specified separator
storage <- strsplit(colnum, split = sep)
# Take/second/third elements and store it into the above vectors
a <- sapply(storage, function(x) x[1])
b <- sapply(storage, function(x) x[2])
c <- sapply(storage, function(x) x[3])
out <- cbind(df, setNames(list(a, b, c), into))
out[setdiff(names(out), names(df)[j1])]
}
myfunc(df)
#. dates a b c
#1 2005-06-29 F 62 130
#2 2005-07-16 F 68 149
#3 2005-12-01 M 68 160
myfunc(df, into = c('a1', 'b1', 'c1'))
# dates a1 b1 c1
#1 2005-06-29 F 62 130
#2 2005-07-16 F 68 149
#3 2005-12-01 M 68 160