2012-11-08 63 views
1

我有一个简单的问题,老实说我试图找到答案。我真的做到了。在R中合并不同长度和缺失值的列

我有一堆已导入到R数据的.csv文件帧

我想利用从每个数据帧的特定列(具有通用名),它合并成一个单一的数据帧将数据框的名称作为列名称,并使用每列生成一个箱形图。

列的长度不一样,并且经常包含NA。

实施例:数据帧(其中,第一行是标题)

数据帧名称Tom

col1 col2 col3 col4 
name1 33 44 55 
name2 33 NA 55 
name3 33 34 55 
name4 33 24 55 

数据帧名称Bob

col1 col2 col3 col4 
name5 33 74 55 
name6 33 NA 55 
name7 33 32 55 

数据帧名称Stu

col1 col2 col3 col4 
name8 33 44 55 
name9 33 11 55 
name10 33 34 55 
name11 33 24 55 
name12 33 32 55 
name13 33 24 5 
name14 33 34 55 
name15 33 24 5 

期望结果

Tom Bob Stu 
44 74 44 
NA NA 11 
34 32 34 
24  24 
      32 
      24 
      34 
      24 

所以,取“COL3”(列名是共享的)从每个数据帧,并仅产生COL3数据的新的数据帧,每一列被命名为它来自的数据框的名称...然后生成汤姆,鲍勃和斯图的并排boxplot(但我可以解决这个问题)。在上面所需结果的空白空间中放置NA是可以的。

+1

在我看来,这将让更多的发送到数据放入长格式? – Dason

回答

1

这里就是我创建使用rbind一个新的合并数据帧中的基本方法,在为每个3个数据帧添加标识符列之后。请注意,您也可以在不首先创建单个数据框的情况下创建Boxplot。

Tom = read.table(header=TRUE, 
text="col1 col2 col3 col4 
name1 33 44 55 
name2 33 NA 55 
name3 33 34 55 
name4 33 24 55") 

Bob = read.table(header=TRUE, 
text="col1 col2 col3 col4 
name5 33 74 55 
name6 33 NA 55 
name7 33 32 55") 

Stu = read.table(header=TRUE, 
text="col1 col2 col3 col4 
name8 33 44 55 
name9 33 11 55 
name10 33 34 55 
name11 33 24 55 
name12 33 32 55 
name13 33 24 5 
name14 33 34 55 
name15 33 24 5") 

# Add a new person identifier column to each data frame. 
Tom$person = "Tom" 
Bob$person = "Bob" 
Stu$person = "Stu" 

# Combine 3 data frames by row. 
dat = rbind(Tom, Bob, Stu) 

dat 
#  col1 col2 col3 col4 person 
# 1 name1 33 44 55 tom 
# 2 name2 33 NA 55 tom 
# 3 name3 33 34 55 tom 
# 4 name4 33 24 55 tom 
# 5 name5 33 74 55 bob 
# 6 name6 33 NA 55 bob 
# 7 name7 33 32 55 bob 
# 8 name8 33 44 55 stu 
# 9 name9 33 11 55 stu 
# 10 name10 33 34 55 stu 
# 11 name11 33 24 55 stu 
# 12 name12 33 32 55 stu 
# 13 name13 33 24 5 stu 
# 14 name14 33 34 55 stu 
# 15 name15 33 24 5 stu 


boxplot(col3 ~ person, data=dat) 

# This would also work, without rearranging the data: 
boxplot(Tom[, "col3"], Bob[, "col3"], Stu[, "col3"]) 

# Save to pdf file. 
pdf("boxplot_1.pdf", height=5, width=5) 
boxplot(col3 ~ person, data=dat, main="Boxplot of three samples.", ylab="col3") 
dev.off() 

enter image description here

+0

完美,谢谢!这工作正常,我现在可以推断它来解决我一直有的其他问题。非常感激。 – user1687421

2

把你在一个名为列表data.frames,llistHmisc包是在这里有用

library(Hmisc) 
data.list <- llist(Tom, Bob, Stu) 
library(reshape2) 
# get a long format version of col3 
col3 <- melt(lapply(data.list, `[[`, 'col3')) 
# the column `L1` contains the names Tom, Bob, Stu 

library(ggplot2) 
# create the boxplots 

ggplot(col3, aes(x=L1, y= value)) + geom_boxplot() 

enter image description here

+0

谢谢..我试图用最少的非标准包来做到这一点,但我也会尝试。 – user1687421

+0

'Hmisc','ggplot2'和'reshape2'都是非常有用的,维护良好的非核心软件包。 – mnel

+0

确实如此,但这是一个程序,希望这个程序可以被那些比我更不胜任的人使用,所以我现在保持简单。 – user1687421