简体   繁体   中英

Condensing Data Frame in R

I just have a simple question, I really appreciate everyones input, you have been a great help to my project. I have an additional question about data frames in R.

I have data frame that looks similar to something like this:

    C <- c("","","","","","","","A","B","D","A","B","D","A","B","D")
    D <- c(NA,NA,NA,2,NA,NA,1,1,4,2,2,5,2,1,4,2)
    G <- list(C=C,D=D)
    T <- as.data.frame(G)
    T
   C  D
1     NA
2     NA
3     NA
4     2
5     NA
6     NA
7     1
8  A  1
9  B  4
10 D  2
11 A  2
12 B  5
13 D  2 
14 A  1
15 B  4
16 D  2 

I would like to be able to condense all the repeat characters into one, and look similar to this:

    J B C E
  1   2 1
  2 A 1 2 1
  3 B 4 5 4
  4 D 2 2 2

So of course, the data is all the same, it is just that it is condensed and new columns are formed to hold the data. I am sure there is an easy way to do it, but from the books I have looked through, I haven't seen anything for this!

EDIT I edited the example because it wasn't working with the answers so far. I wonder if the NA's, blanks, and unevenness from the blanks are contributing??

This seems to get the results you are looking for. I'm assuming it's OK to remove the NA values since that matches the desired output you show.

T <- na.omit(T)
T$ind <- ave(1:nrow(T), T$C, FUN = seq_along)
reshape(T, direction = "wide", idvar = "C", timevar = "ind")
#    C D.1 D.2 D.3
# 4      2   1  NA
# 8  A   1   2   1
# 9  B   4   5   4
# 10 D   2   2   2

library(reshape2)
dcast(T, C ~ ind, value.var = "D", fill = "")
#   C 1 2 3
# 1   2 1  
# 2 A 1 2 1
# 3 B 4 5 4
# 4 D 2 2 2

here´sa reshape solution:

require(reshape)
cast(T, C ~ ., function(x) x)

Changed T to df to avoid a bad habit. Returns a list, which my not be what you want but you can convert from there.

C <- c("A","B","D","A","B","D","A","B","D")
D <- c(1,4,2,2,5,2,1,4,2)
my.df <- data.frame(id=C,val=D)

ret <- function(x) x
by.df <- by(my.df$val,INDICES=my.df$id,ret)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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