【问题标题】:Loops in R to split columns and rename then combined in a dataframeR中的循环以拆分列并重命名,然后在数据框中组合
【发布时间】:2020-05-06 14:21:21
【问题描述】:

我试图用“。”分割数据框中的一些列。然后根据原始名称重命名拆分的列。 Original dataset Expect result

library(ISLR)
wage <- Wage #sample dataset from ISLR
wage_term_ref <- as.data.frame(wage[,3:9]) # These are the columns I need to split

colnames(wage_term_ref)

“maritl”“种族”“教育”“地区”“工作类别”“健康”“health_ins”

wage_term_ref[] <- lapply(wage_term_ref, as.character) # change all from factor to character

martil<- data.frame(do.call(rbind, strsplit(wage_term_ref$maritl, "[.]" ))) # split the first columne
names(martil)<-c("martil_Index","martil_Status") # rename the splited columns based on the original name "martil"

然后我需要对工资期限参考中的余额 6 列重复相同的操作。 最后将所有 _Index 列(例如.martil_Index)和工资[,1:2] 合并到一个新的数据框“wage_updated”

有没有人有更好的方法来做到这一点?也许是一个循环?提前致谢。

【问题讨论】:

    标签: r


    【解决方案1】:

    如果您想在同一个分隔符上拆分多个列,您可以使用 cSplit 中的 splitstackshape 来简化此过程。

    splitstackshape::cSplit(wage_term_ref, names(wage_term_ref), '.')
    

    这会自动将_1_2 添加到每个列名。

    【讨论】:

      【解决方案2】:

      基础 R 解决方案:

      #install.packages("ISLR", dependencies = TRUE)
      library(ISLR)
      
      # Import dataset from ISLR library, store copy: wage => data.frame
      wage <- Wage #sample dataset from ISLR
      
      # Boolean vector of vectors to split: split_col => vector of booleans
      split_col <- sapply(wage, function(x){if(!(is.numeric(x))){any(grepl("[.]", x))}else{FALSE}})
      
      # Create an empty list to store subsets from the wage data.frame: wage_list => list
      wage_list <- vector("list", ncol(wage[,split_col]))
      
      # Populate the list with vectors split on ".": wage_list => list
      wage_list <- lapply(wage[,split_col], function(y){strsplit(as.character(y), "[.]")})
      
      # Calculate the maximum number of vectors per list element in the wage_list: 
      # max_lengths_per_el => list of named numeric vectors
      max_lengths_per_el <- sapply(wage_list, function(z){max(lengths(z))})
      
      # Convert each list element to a data.frame and name appropriately: 
      # wage_list => list of data.frames
      wage_list <- lapply(seq_along(wage_list), function(i){
        setNames(data.frame(do.call("rbind", wage_list[[i]]), row.names = NULL),
                 paste(names(wage_list)[i], 1:max_lengths_per_el[i], sep = "_"))
        }
      )
      
      # Column bind the original data.set (excluding the columns that have been split)
      # with a data.frame of the column-binded lists: wage_df => data.frame
      wage_df <- cbind(wage[,!split_col], do.call("cbind", wage_list))
      

      【讨论】:

      • Thx,我已更改最后一行以进行列选择和重命名,它工作正常。 # 工资列表 [[, 1) # 工资_df
      • @TYL 不用担心,如果您觉得我的解决方案有用,请点赞。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-15
      • 2016-11-09
      • 1970-01-01
      • 1970-01-01
      • 2014-11-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多