-4

Consider i have this dataframe in R

https://i.stack.imgur.com/SV92V.png

how can i transform this into :

https://i.stack.imgur.com/XkIss.png

I have these multiple columns with same names. So now i have to keep all unique column names and somehow insert their values in row wise fashion

Chris Cudmore
  • 29,793
  • 12
  • 57
  • 94
Neeraj
  • 1
  • 1
  • 2
    Please format your code using the SO code editing tools. You mention a `data.frame` but show what looks like a vector of strings. I also don't understand your expected output. How do you get `6` as the fourth element? – Maurits Evers Jul 31 '18 at 00:47
  • Also - please explain the logic in a clear fashion – MSW Data Jul 31 '18 at 00:51
  • 1
    @Neeraj Screenshots of your data are not useful, since we can't copy & paste. Use `dput`. Better yet, take a look at how to provide a [minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – Maurits Evers Jul 31 '18 at 00:54
  • I have these multiple columns with same names. So now i have to keep all unique column names and somehow insert their values in row wise fashion – Neeraj Jul 31 '18 at 01:04
  • @Neeraj You must read the link I gave on how to provide a reprex. Your problem statement is not clear. Screenshots of data don't help. – Maurits Evers Jul 31 '18 at 01:42

1 Answers1

0

You can use the script below:

df <- data.frame(matrix(c(1:7), ncol = 7))
names(df) <- c(rep("a", 4), rep("b", 3))
dfi <- as.data.frame(t(df))
dfi$id <- factor(names(df))
max_n <- max(tapply(dfi$V1, dfi$id, length))

ll <- split(dfi, dfi$id)
df_out <- as.data.frame(sapply(ll, function(x) {
    c(x$V1, rep(NA, max_n - length(x$V1)))  
}))

df_out

Output:

  a  b
1 1  5
2 2  6
3 3  7
4 4 NA
Artem
  • 3,304
  • 3
  • 18
  • 41