user1987607
user1987607

Reputation: 2157

extract values after first character in data frame column

I have the following dataframe

df <- data.frame(V1 = c(1, 2), V2 = c(10, 20), V3=c("9,1", "13,3,4"))

> df
  V1 V2     V3
1  1 10    9,1
2  2 20 13,3,4

Now I want to create a new column 'V4' that takes the value after the first ',' from V3, divides it by the value in V2 and multiplies that by 100

In my example this would be:

(1 divided by 10) * 100 = 10 (3 divided by 20) * 100 = 15

So the output would look like this

df_new 

  V1 V2     V3    V4
1  1 10    9,1    10
2  2 20 13,3,4    15  

How can this be achieved?

Upvotes: 0

Views: 37

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389325

We can use regex to extract the number after first comma divide it by V2 and multiply by 100.

transform(df, V4 = as.integer(sub("\\d+,(\\d+).*", "\\1", V3))/V2 * 100)
#  V1 V2     V3 V4
#1  1 10    9,1 10
#2  2 20 13,3,4 15

Upvotes: 1

Related Questions