Home > other >  How do I Split a column in R?
How do I Split a column in R?

Time:11-21

I have a dataset like this.

enter image description here

As you can see in the column "Year" there is not only the year. There is also other information that I would need to move into a different column. Does anybody have any idea of how to do it? Thank you in advance

I tried many things but none of the was successful

CodePudding user response:

How about separate() from the tidyr package:

library(tidyr)
dat <- data.frame(x =c("1994 2 3.69 2.4", 
                       "1998 16 24.33 5.28"))
dat
#>                    x
#> 1    1994 2 3.69 2.4
#> 2 1998 16 24.33 5.28
separate(dat, x, c("year", "v1", "v2", "v3"), sep = " ")
#>   year v1    v2   v3
#> 1 1994  2  3.69  2.4
#> 2 1998 16 24.33 5.28

Created on 2022-11-20 by the reprex package (v2.0.1)

CodePudding user response:

We may use read.table from base R

read.table(text = df1$x, header = FALSE)

-output

    V1 V2    V3   V4
1 1994  2  3.69 2.40
2 1998 16 24.33 5.28

data

df1 <- structure(list(x = c("1994 2 3.69 2.4", 
"1998 16 24.33 5.28")), class = "data.frame", row.names = c(NA, 
-2L))
  • Related