R将对转换为data.frame

栏目: R语言 · 发布时间: 6年前

内容简介:翻译自:https://stackoverflow.com/questions/8127869/r-convert-key-val-pair-into-data-frame

在R中,我有两个对的向量,如下所示:

x <- c("A=5", "B=1",        "D=1", "E=1", "F=2", "G=1")
y <- c("A=2", "B=1", "C=3", "D=1",                     "H=4")

我想将其转换为data.frame,如下所示:

A B C D E F G H
x 5 1 0 1 1 2 1 0
y 2 1 3 1 0 0 0 4

x或y中包含的所有键都应构成列,未出现在x或y中的键应添加值为零.

不是最漂亮的解决方案,但很容易遵循:

1)将字符串解析为数据框:

df1 <- as.data.frame(sapply(strsplit(x, '='), rbind), stringsAsFactors=FALSE)

结果:

> as.data.frame(sapply(strsplit(x, '='), rbind), stringsAsFactors=FALSE)
  V1 V2 V3 V4 V5 V6
1  A  B  D  E  F  G
2  5  1  1  1  2  1

2)给标题:

names(df1) <- df1[1,]
df1 <- df1[-1,]

结果:

> df1
  A B D E F G
2 5 1 1 1 2 1

3)对你的其他字符串做同样的事情:

df2 <- as.data.frame(sapply(strsplit(y, '='), rbind), stringsAsFactors=FALSE)
names(df2) <- df2[1,]
df2 <- df2[-1,]

4)合并那些:

df <- merge(df1, df2, all=TRUE, sort=TRUE)

结果:

> df
  A B D    E    F    G    C    H
1 2 1 1 <NA> <NA> <NA>    3    4
2 5 1 1    1    2    1 <NA> <NA>

更新:基于评论的上述多功能一体化妆:

> df1 <- as.data.frame(sapply(strsplit(x, '='), rbind), stringsAsFactors=FALSE)
> names(df1) <- df1[1,]
> df1 <- df1[-1,]
> 
> df2 <- as.data.frame(sapply(strsplit(y, '='), rbind), stringsAsFactors=FALSE)
> names(df2) <- df2[1,]
> df2 <- df2[-1,]
> 
> library(reshape)
> df <- rbind.fill(df1,df2)
> df[is.na(df)] <- 0
> df <- df[, order(names(df))]
> df
  A B C D E F G H
1 5 1 0 1 1 2 1 0
2 2 1 3 1 0 0 0 4

翻译自:https://stackoverflow.com/questions/8127869/r-convert-key-val-pair-into-data-frame


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Essential ActionScript 3.0

Essential ActionScript 3.0

Colin Moock / Adobe Dev Library / June 22, 2007 / $34.64

ActionScript 3.0 is a huge upgrade to Flash's programming language. The enhancements to ActionScript's performance, feature set, ease of use, cleanliness, and sophistication are considerable. Essentia......一起来看看 《Essential ActionScript 3.0》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换