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
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
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.