I have a data frame with multiple columns in R. I want to split the "age" column into two column, each with one string in it.
fas value age colony
1: C12:0 0.002221915 LO 7_13
2: C13:0 0.000770179 LO 7_13
3: C14:0 0.004525352 LO 7_13
4: C15:0 0.000738928 LO 7_13
5: C16:1a 0.002964627 LO 7_13
Output:
fas value size age colony
1: C12:0 0.002221915 L O 7_13
2: C13:0 0.000770179 L O 7_13
3: C14:0 0.004525352 L O 7_13
4: C15:0 0.000738928 L O 7_13
5: C16:1a 0.002964627 L O 7_13
I tried:
data_frame<-str_split_fixed(df$age, "", 2)
Use the split() function in R to split a vector or data frame. Use the unsplit() method to retrieve the split vector or data frame.
The split() function in R can be used to split data into groups based on factor levels. This function uses the following basic syntax: split(x, f, …)
Use str_split to Split String by Delimiter in R Alternatively, the str_split function can also be utilized to split string by delimiter. str_split is part of the stringr package. It almost works in the same way as strsplit does, except that str_split also takes regular expressions as the pattern.
Subset a Data Frame with Base R Extract[] If subsetting is done by only rows or only columns, then leave the other value blank. For example, to subset the d data frame only by rows, the general form reduces to d[rows,] . Similarly, to subset only by columns, d[,cols] .
With base R:
df$size <- substr(df$age,1,1)
df$age <- substr(df$age,2,2)
And to get the result in the column order you specified:
df[,c("fas","value","age","size","colony")]
fas value age size colony
1 C12:0 0.002221915 O L 7_13
2 C13:0 0.000770179 O L 7_13
3 C14:0 0.004525352 O L 7_13
4 C15:0 0.000738928 O L 7_13
5 C16:1a 0.002964627 O L 7_13
You can use sub
and backreference:
df$age <- sub("(^\\w)(\\w$)", "\\1", df$age)
df$size <- sub("(^\\w)(\\w$)", "\\2", df$age)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With