如何用 map 替换这个 for 循环以获得 data.frames 列表? [英] How do I replace this for-loop with map for a list of data.frames?

查看:28
本文介绍了如何用 map 替换这个 for 循环以获得 data.frames 列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 data.frameslist,我想使用 as.numeric()<将其转换为 binary 变量/代码>.

I have a list of data.frames that I want to convert into binary variables using as.numeric().

我正在寻找替换这个脚本,

I am looking to replace this script,

data_list <- list(
        mtcars,
        diamonds
)


for (i in 1:length(data_list)) {
        

        # extract data;
        temp_data <- data_list[[i]]
        
        # extract lenght;
        col_length <- ncol(temp_data)
        
        
        for (j in 1:col_length) {
                
                # Only do the operation if it is a numeric/double
                # class variable
                if (inherits(temp_data[,j], c("numeric", "double"))) {
                        
                        temp_data[,j] <- as.numeric(
                                temp_data[,j] > 1
                        )
                        
                        
                } else {
                        
                        next()
                        
                }
                
                
                
        }
        
        # Store it back to the list
        data_list[[i]] = temp_data
 
        
}

具有 tidyverse- 和 map- 类型的解决方案.

with a tidyverse- and map-type of solution.

推荐答案

您可以使用 mutateacross 并添加 selection helper where() 对您想要的 class 变量进行操作.

You can use mutate with across and add the selection helper where() to do your operation on your desired class of variables.

data_list <- list(
        mtcars,
        iris
)

data_list <- data_list %>% map(
        ~ .x %>% mutate(
                across(where(is.numeric), ~ as.numeric(. > 1))
        )
)

across(where(is.numeric), ~ as.numeric(. > 1)) 查找所有 numeric 变量 across您的 data.frame 并将它们单独转换为 binary 变量.

The across(where(is.numeric), ~ as.numeric(. > 1)) finds all numeric variables across your data.frame and converts them individually to binary variables.

这篇关于如何用 map 替换这个 for 循环以获得 data.frames 列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆