【问题标题】:looping over variables of a data.frame leading one final data.frame in R循环遍历 R 中最后一个 data.frame 的 data.frame 的变量
【发布时间】:2020-04-26 21:06:16
【问题描述】:

我编写了一个函数,用于将 data.frame 中的任何一个变量(即列)更改为其唯一级别并返回更改后的 data.frame。

我想知道如何使用我的函数一次更改多个变量获得一个包含所有更改的最终 data.frame

我尝试了以下方法,但这会提供多个 data.frames 而只有 last data.frame所需的输出

data <- data.frame(sid = c(33,33, 41), pid = c('Bob', 'Bob', 'Jim'))

#== My function for ONE variable:
f <- function(data, what){
 data[[what]] <- as.numeric(factor(data[[what]], levels = unique(data[[what]])))
 return(data)
}  

# Looping over `what`:
what <- c('sid', 'pid')
lapply(seq_along(what), function(i) f(data, what[i]))

【问题讨论】:

    标签: r dataframe lapply


    【解决方案1】:

    在函数中,我们可以将return改为data[[what]]

    f <- function(data, what){
       data[[what]] <- as.numeric(factor(data[[what]], levels = unique(data[[what]])))
       data[[what]]
      }  
    
    data[what] <- lapply(seq_along(what), function(i) f(data, what[i]))
    

    或者做

    data[what] <-  lapply(what, function(x) f(data, x))
    

    或者干脆

    data[what] <- lapply(what, f, data = data)
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-17
    • 1970-01-01
    • 2015-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多