动态生成数据框值列名

时间:2018-03-08 20:08:20

标签: r dplyr purrr

我正在尝试在列中获取值以设置为列名。冒号前面的字符应该是列名。

df = cbind.data.frame(
    id = c(1, 2 ,3, 4, 5),
    characteristics_ch1 = c("gender: Female", "gender: Male", "gender: Female", "gender: Male", "gender: Female"),
    characteristics_ch1.1 = c("Thing One: a", "Thing One: a", "Thing One: a", "Thing One: b", "Thing One: b"),
    characteristics_ch1.2 = c("age: 60", "age: 45", "age: 63", "age: 56", "age: 65"))

对于第2-5列,我想删除“gender:”,“Thing One:”和“age:”,将它们作为各自列的名称。

结果数据框将是:

Result = cbind.data.frame(
        id = c(1, 2 ,3, 4, 5),
        gender = c("Female", "Male", "Female", "Male", "Female"),
        `Thing One` = c("a", "a", "a", "b", "b"),
        age = c("60", "45", "63", "56", "65")
)

为此,我正在运行以下功能:

re_col = function(i){
        new_name = str_split_fixed(i, ": ", 2)[1]
        return(assign(new_name, str_split_fixed(i, ": ", 2)[,2]))
}

通过以下申请功能:

plyr::colwise(re_col)(df)

#and

purrr::map(df, re_col)

没有成功。

也可能有更好的方法。我最初尝试编写一个可以与数据清理中的dplyr一起使用的函数,作为%>%步骤,但是不成功。

2 个答案:

答案 0 :(得分:1)

一种解决方法,使用stringi通过提供给指定列的正则表达式模式拆分数据值

rename.df_cols <- function(df, rgx_pattern = NULL, col_idx = NULL,...){
    if(max(col_idx) > ncol(df)){
        col_idx <- min(col_idx):ncol(df)
    }
    o <- lapply(col_idx, function(i){

        parts <- stri_split_regex(df[[i]], rgx_pattern, simplify = T)
        col_name <- unique(parts[,1])
        new_dat <- parts[,2]

        colnames(df)[[i]] <<- col_name
        df[[i]] <<- new_dat
    })
    return(df)
}

> df
  id characteristics_ch1 characteristics_ch1.1 characteristics_ch1.2
1  1      gender: Female          Thing One: a               age: 60
2  2        gender: Male          Thing One: a               age: 45
3  3      gender: Female          Thing One: a               age: 63
4  4        gender: Male          Thing One: b               age: 56
5  5      gender: Female          Thing One: b               age: 65
> rename.df_cols(df = df, col_idx = 2:4, rgx_pattern = "(\\s+)?\\:(\\s+)?")
  id gender Thing One age
1  1 Female         a  60
2  2   Male         a  45
3  3 Female         a  63
4  4   Male         b  56
5  5 Female         b  65

这就是你要找的东西吗?

用烟斗编辑:

> df %>% rename.df_cols(rgx_pattern = "(\\s+)?\\:(\\s+)?", col_idx = 2:5)
  id gender Thing One age
1  1 Female         a  60
2  2   Male         a  45
3  3 Female         a  63
4  4   Male         b  56
5  5 Female         b  65

答案 1 :(得分:1)

我们可以gather将数据框格式化为长格式,separate将值列:,然后spread将数据框格式化为宽格式。< / p>

library(tidyverse)

df2 <- df %>%
  gather(Column, Value, -id) %>%
  separate(Value, into = c("New_Column", "Value"), sep = ": ") %>%
  select(-Column) %>%
  spread(New_Column, Value, convert = TRUE)
df2
#   id age gender Thing One
# 1  1  60 Female         a
# 2  2  45   Male         a
# 3  3  63 Female         a
# 4  4  56   Male         b
# 5  5  65 Female         b
相关问题