R语言 将列名中的字符拆分为行中具有逻辑值的新列

jw5wzhpr  于 2023-03-27  发布在  其他
关注(0)|答案(3)|浏览(128)

我试图将列名字符串拆分为单独的列,但我面临的问题是行具有逻辑值。有几篇文章将行中的字符串拆分为列,但我找不到任何具有逻辑值的文章。
我的data.frame看起来像这样:

mydf <- data.frame (author = c("N1", "N2", "N3"),
Aa..Ab = c(T, T, F),
BB = c(T, F, T),
Ca...Cb = c(F, F, T))

结果应该如下所示

mydfnew <- data.frame (author = c("N1", "N2", "N3"),
 Aa = c(T, T, F),
 Ab = c(T, T, F),
 BB = c(T, F, T),
 Ca = c(F, F, T),
 Cb = c(F, F, T))

我尝试调整拆分列和名称的代码(Split character in column and name),如下所示:

splitCol <- function(dataframe, splitVars=names(dataframe)){
  split.DF <- dataframe[,splitVars]
  keep.DF <- dataframe[, !names(dataframe) %in% c(splitVars)]

  X <- function(x)matrix(unlist(rep(x)), byrow=TRUE)

  newdf <- as.data.frame(do.call(cbind, suppressWarnings(lapply(split.DF, X))) )
  names(newdf) <- paste(rep(names(split.DF), each=2), c(".a", ".b"), sep="") 
  data.frame(keep.DF,newdf)
}

打电话时

splitCol(mydf)

我得到错误:
错误在names(newdf)〈- paste(rep(names(split.DF),each = 2),c(“.a”,:'names'属性[8]必须与vector [4]的长度相同

gk7wooem

gk7wooem1#

下面是使用replicateMap的方法

as.data.frame(Map(x = strsplit(names(mydf), '[.]+'), 
                  DATA = mydf, 
                  f = function(x,DATA){
                    setNames(replicate(length(x), DATA, simplify = FALSE),x  )}
             ))
##    author    Aa    Ab    BB    Ca    Cb
##  1     N1  TRUE  TRUE  TRUE FALSE FALSE
##  2     N2  TRUE  TRUE FALSE FALSE FALSE
##  3     N3 FALSE FALSE  TRUE  TRUE  TRUE
z9gpfhce

z9gpfhce2#

一个答案,本质上是@mnel版本的两步变化:

splnames <- strsplit(names(mydf),"\\.+")
setNames(data.frame(rep(mydf,sapply(splnames,length))),unlist(splnames))

结果:

author    Aa    Ab    BB    Ca    Cb
1     N1  TRUE  TRUE  TRUE FALSE FALSE
2     N2  TRUE  TRUE FALSE FALSE FALSE
3     N3 FALSE FALSE  TRUE  TRUE  TRUE
ua4mk5z4

ua4mk5z43#

这里有一个使用“reshape 2”包和我的“splitstackshape”包的替代方案。基本思想是获得一个“长”数据集,它比宽数据集更容易操作-即使最终目标是创建一个宽数据集:)

## Load required packages
library(reshape2)
library(splitstackshape)

## Create a "long" version of your dataset
A <- melt(mydf, id.vars="author")
B <- concat.split.multiple(A, "variable", ".", "long")

## Use `dcast` to get the desired wide form
## Use `na.omit(B)` to get rid of the rows that have 
##   NA before doing the transformation
dcast(na.omit(B), author ~ variable, value.var="value")
#   author    Aa    BB    Ca    Ab    Cb
# 1     N1  TRUE  TRUE FALSE  TRUE FALSE
# 2     N2  TRUE FALSE FALSE  TRUE FALSE
# 3     N3 FALSE  TRUE  TRUE FALSE  TRUE

相关问题