Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Apply substr to each element of a dataframe column

Tags:

r

this is my situation: I have a dataframe and I want to apply the substr function to each element of a specific column. The column I want to manipulate containes expressions like:

x = c("name1_01", "name2_02", "name3_01")
df = data.frame(x)
colnames(df) = ("Names")
df["Names"] = sapply(df["Names"], as.character)
df
# Names
# 1 name1_01
# 2 name2_01
# 3 name3_01

Now I want to chop off the last 3 digits of each entry in the specific column. I simply tried substr which doesn't me what I want:

df["Names"] = substr(df["Names"], 1,5)
df["Names"]
# Names
# 1 c("name1
# 2 c("name1
# 3 c("name1

If I however apply substr to single elements I do get the right result:

df[1,"Names"] = substr(df[1,"Names"], 1,5)
df[1,"Names"]
# Names
# [1,] "name1"

I already tried around a lot (I also tried sapply for substr) but I don't get it. I am quite new to R and hopefully the solution is quite obvious...

Thank all of you in advance, Chris!

like image 964
ChriiSchee Avatar asked Oct 20 '25 04:10

ChriiSchee


1 Answers

Using mutate() from dplyr:

library(dplyr)
df %>%
  mutate(Names = substr(Names, 1, 5))
like image 155
Steven Beaupré Avatar answered Oct 21 '25 18:10

Steven Beaupré



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!