【发布时间】:2020-04-27 02:27:11
【问题描述】:
我正在尝试屏蔽用户在 BASE R 中的 data.frame 中请求的变量 (what)。我已经编写了函数 foo 来为 data.frame 中请求的数字变量实现此目标。
但我想知道如何屏蔽字符变量(例如,下面示例中的pid)?
具体来说,下面是我的data.frame、我的函数foo 和期望的输出。
dat <- data.frame(sid = c(33,33,41,42,49,51), pid = c('Bob', 'Bob', 'Jim', 'John', 'Carol smith', 'Cathy'))
#== function `foo`:
foo <- function(data, what){
f <- function(data, what){
data[[what]] <- as.numeric(factor(data[[what]], levels = unique(data[[what]])))
return(data[what])
}
data[what] <- lapply(what, f, data = data)
return(data)
}
#== Example of use:
foo(dat, c('sid', 'pid'))
desired.output1 <- data.frame(sid = c(1,1,2, 3,4,5), pid = c('B', 'B', 'Ji', 'Jo', 'Car', 'Cat'))
desired.output2 <- data.frame(sid = c(1,1,2, 3,4,5), pid = c('B', 'B', 'J.1', 'J.2', 'C.1', 'C.2'))
【问题讨论】: