Consider i have this dataframe in R
how can i transform this into :
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
Consider i have this dataframe in R
how can i transform this into :
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
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