2014-09-02 81 views
1
input <- read.table(header=F, text="abc 2 
       def 3 
       pq 2") 
colnames(input) <- c("text","count") 

我输入的是文本及其在数据中出现的次数。 我想获得将重复显示计数的次数的文本行的输出。我正在努力寻找任何可以轻松完成的功能。R - 根据计数器值创建行

预期输出:

output <- read.table(header=F, text="abc 2 
       abc 2 
       def 3 
       def 3 
       def 3 
       pq 2 
       pq 2 ") 
colnames(output) <- c("text","count") 

任何帮助将不胜感激!

回答

0

by应该对此做出快速的工作。刚处理按行输入,然后后加入了这一切:

output <- do.call(rbind, by(input, rownames(input), function(x) { 
    data.frame(text=rep(x$text, x$count), x$count) 
})) 
rownames(output) <- NULL 
colnames(output) <- c("text","count") 
print(output) 

## text count 
## 1 abc  2 
## 2 abc  2 
## 3 def  3 
## 4 def  3 
## 5 def  3 
## 6 pq  2 
## 7 pq  2 
+0

谢谢大家。我最终使用了David的解决方案。学习了很多不同的方法来实现输出。 – 2014-09-03 14:06:59

2

或者

as.data.frame(lapply(input, function(x) rep(x, input$count))) 
# text count 
# 1 abc  2 
# 2 abc  2 
# 3 def  3 
# 4 def  3 
# 5 def  3 
# 6 pq  2 
# 7 pq  2 
+0

虽然它的工作原理似乎有点奇怪,重复每一列的值重复行。 – thelatemail 2014-09-02 23:50:16

+0

@thelatemail,不知道你的意思。我认为如果你将代码分解成部分,你将会得到逻辑。这是我想起来的第一件事...... – 2014-09-02 23:51:59

+0

我明白这是如何工作的,但看到我的答案只是使用索引来重复行。它需要为数据集的每一列重复“rep”。如果你重复行,那么在行上而不是在列上操作似乎是有意义的。 – thelatemail 2014-09-02 23:53:34

1

使用行索引:

input[rep(seq(nrow(input)),input$count),] 
# or even 
input[rep(rownames(input),input$count),] 

# text count 
#1 abc  2 
#1.1 abc  2 
#2 def  3 
#2.1 def  3 
#2.2 def  3 
#3  pq  2 
#3.1 pq  2 

第二种选择工作,因为你可以索引由字符向量rownames以及colnames,例如:

rownames(input) 
#[1] "1" "2" "3" 
input["1",] 
# text count 
#1 abc  2 
2

使用data.table

library(data.table) 
setDT(input)[, .SD[rep(1:.N, count)]] 
# text count 
#1: abc  2 
#2: abc  2 
#3: def  3 
#4: def  3 
#5: def  3 
#6: pq  2 
#7: pq  2 

或者

setDT(input)[input[,rep(1:.N, count)]] 
0

你可以使用rep

with(input, { 
    data.frame(text = rep(levels(text), count), count = rep(count, count)) 
}) 

或者,使用一个辅助功能。两者都返回以下内容。 inp输入数据中

f <- function(j, k) rep(j, k) 
data.frame(text = inp$text[f(inp[,1], inp[,2])], count = f(inp[,2], inp[,2])) 
# text count 
#1 abc  2 
#2 abc  2 
#3 def  3 
#4 def  3 
#5 def  3 
#6 pq  2 
#7 pq  2