bvowe
bvowe

Reputation: 3384

R Data.Table Split Numeric Column and Do Operation

data=data.frame("VAR1"= c(105,607,111),
"VAR2"=c(7,19,13))

I have VAR1 and wish to create VAR2 with a simple rule, I take the first digit from VAR1 and multiply it by 2 and then add the last two numbers, so it looks like this for digit 111 in VAR1: 2*1 + 11 = 13.

Upvotes: 0

Views: 57

Answers (3)

Chris Ruehlemann
Chris Ruehlemann

Reputation: 21400

First split the vector into individual elements, making sure they're numeric:

Split <- lapply(strsplit(data$VAR1, split = ""), as.numeric)

Then use sapply in this way:

data$VAR2 <- sapply(Split, function(x){
  sum(x[1]*2 + as.numeric(paste0(x[2], x[3])))
})

data
  VAR1 VAR2
1  105    7
2  607   19
3  111   13

Upvotes: 0

s_baldur
s_baldur

Reputation: 33488

Assuming we are always dealing with 3-digit numbers:

with(data, 2 * (VAR1 %/% 100) + VAR1 %% 100)

or

with(data, 2 * floor(VAR1 / 100) + VAR1 %% 100)

Since the post is tagged with data.table:

setDT(data)
data[, VAR2 := 2 * floor(VAR1 / 100) + VAR1 %% 100]
data

   VAR1 VAR2
1:  105    7
2:  607   19
3:  111   13

Upvotes: 1

Matt
Matt

Reputation: 2987

Using data.table:

library(data.table)

data <- data.table("VAR1"= c(105,607,111))

data[, VAR2 := as.numeric(substr(VAR1, 1, 1)) * 2 + as.numeric(substr(VAR1, 2, 3))]

  VAR1 VAR2
1:  105    7
2:  607   19
3:  111   13

Upvotes: 2

Related Questions