0

My question is so basic but i could't do nothing, i'm a newbie in R. I have a column like this

column
val1
val2
ppp
val3
val4

How can i turn that like this?

column ppp
val1   val3
val2   val4
Alessander
  • 43
  • 4
  • Is this the full dataset you have? or are you trying to do a similar thing for a much bigger dataset – M_Shimal Mar 10 '20 at 02:55
  • 1
    please add the data using `dput`. see [here](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). Is the input a data.frame? is the output also a dataframe? Is the additional column name always haf way down the input? – dww Mar 10 '20 at 02:57
  • id find all the rownumbers for rows that have 'ppp', then use that to split it. Had without your full data to show code though – morgan121 Mar 10 '20 at 03:44

1 Answers1

0

Your data is probably a vector, not a column, because if it were a column, it would be a part of a dataframe, and you couldn't split it like that, without rearranging all the other rows, which you have not shown. Or maybe it could be a dataframe with just one column. If that is the case, the change to the code is trivial.

your_vector <- c("column", "val1", "val2", "ppp", "val3", "val4")
key <- "ppp"
i <- which(your_vector == key)
new_df <- data.frame(
  your_vector[2:(i-1)],
  your_vector[(i+1):length(your_vector)],
  stringsAsFactors = F
)
colnames(new_df) <- c(your_vector[1], your_vector[i])

This code assumes that there is one value in the vector, containing the given key, and it must be at the very middle, otherwise you wouldn't be able to split it and pair the two columns with the same length. Anything else will cause an error. But, if it is in the middle, you wouldn't need to find it, you could just calculate the mid position in the vector and split it. So I think you need to think a bit more about this problem.

user2332849
  • 1,421
  • 1
  • 9
  • 12