繁体   English   中英

如何将数据帧转换为 R 中的 csv 文件

[英]How to convert a dataframe into a csv file in R

我有一个看起来像这样的数据框:

ID  Region   
1   a b c d 
2   b c d e g
3   a c e f g h
.
.
.

我想把它放到一个看起来像这样的 csv 文件中

ID   a b c d e f g h
1    1 1 1 1 NA NA NA NA 
2    NA 1 1 1 1 NA 1 NA
3    1 NA 1 NA 1 1 1 1
.
.
.

我可以将数据帧转换为 csv 文件,但不知道如何以这种方式格式化。 任何帮助将不胜感激!

如果您的数据框如下所示:

df <- data.frame(ID = 1:3,  Region = c("a b c d", "b c d e g", "a c e f g h"))

df
#>   ID      Region
#> 1  1     a b c d
#> 2  2   b c d e g
#> 3  3 a c e f g h

你有一个你想要定义的所有可能区域的向量:

all_regions <- c("a", "b", "c", "d", "e", "f", "g", "h")

然后你可以这样做:

cbind(ID = df$ID,
      setNames(as.data.frame(t(sapply(strsplit(df$Region, " "), 
               function(x) as.numeric(all_regions %in% x)))),
               all_names))
#>   ID a b c d e f g h
#> 1  1 1 1 1 1 0 0 0 0
#> 2  2 0 1 1 1 1 0 1 0
#> 3  3 1 0 1 0 1 1 1 1

使用 reshape2

library(reshape2)
df2=melt(strsplit(df$Region,""))
df2=df2[df2$value!=" ",]
df2=dcast(df2,L1~value)
ifelse(is.na(df2),NA,1)

     L1  a  b c  d  e  f  g  h
[1,]  1  1  1 1  1 NA NA NA NA
[2,]  1 NA  1 1  1  1 NA  1 NA
[3,]  1  1 NA 1 NA  1  1  1  1

cSplit_e也有一个选项

library(splitstackshape)
out <- cSplit_e(df, 'Region', type = 'character', drop = TRUE, sep=" ")
names(out) <- sub("Region_", "", names(out))

-输出

> out
  ID  a  b c  d  e  f  g  h
1  1  1  1 1  1 NA NA NA NA
2  2 NA  1 1  1  1 NA  1 NA
3  3  1 NA 1 NA  1  1  1  1

数据

df <- structure(list(ID = 1:3, Region = c("a b c d", "b c d e g", "a c e f g h"
)), class = "data.frame", row.names = c(NA, -3L))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM