Does R transform() overwrite each value? -


i need update value of particular column, if column matches condition. here sample:

zz1 <- "or,d,ddate,rdate,changes,class,price,fdate,company,number,minutes,added,source va1,va2,2014-05-24,,0,0,2124,2014-05-22 15:50:16,,,,2014-05-22 12:20:03,ss va1,va2,2014-05-26,,0,0,2124,2014-05-22 15:03:44,,,,2014-05-22 12:20:03,s1 va1,va2,2014-06-05,,0,0,2124,2014-05-22 15:48:24,,,,2014-05-22 12:20:03,s1 va1,va2,2014-06-09,,0,0,2124,2014-05-22 15:37:35,,,,2014-05-22 12:20:03,s2 va1,va2,2014-06-16,,0,0,2124,2014-05-22 14:17:33,,,,2014-05-22 12:20:03,ss"  columnclasses <- c("factor", "factor", "posixct", "factor", "integer", "factor", "integer", "factor", "factor", "factor", "integer", "factor", "factor") dt1 <- read.table(text=zz1, header = true, sep = ",", comment.char = "", quote = "", na.strings = c(""), colclasses = columnclasses) 

the first column (or) value should changed combined value of columns or , d sources equal ss , s2.

i've tried below:

dt1$or[dt1$source == "ss" | dt1$source == "s2"] <- paste0(dt1$or, as.character(dt1$d)) 

but returns error number of items replace not multiple of replacement length.

now following code:

dt1$or <- as.character(dt1$or) dt1 <- transform(dt1, or = ifelse(source == "ss" | source == "s2", paste0(dt1$or, as.character(dt1$d)), dt1$or)) 

it works well, afraid re-writes each value sources not equal ss , s2. if true, how should change code avoid it?

first of all, judging previous questions, using data.table until now, lets keep way , use fread instead read.table.

so first step be:

library(data.table) dt1 <- fread(zz1, colclasses = columnclasses) 

second step, key data source (bad name column btw) , perform binary join in order avoid (correctly mentioned you) overhead of ifelse, namely:

setkey(dt1, source) dt1[.(c("ss", "s2")), or := paste0(or, d)][] #        or   d      ddate rdate changes class price               fdate company number minutes               added source # 1:    va1 va2 2014-05-26    na       0     0  2124 2014-05-22 15:03:44      na     na      na 2014-05-22 12:20:03     s1 # 2:    va1 va2 2014-06-05    na       0     0  2124 2014-05-22 15:48:24      na     na      na 2014-05-22 12:20:03     s1 # 3: va1va2 va2 2014-06-09    na       0     0  2124 2014-05-22 15:37:35      na     na      na 2014-05-22 12:20:03     s2 # 4: va1va2 va2 2014-05-24    na       0     0  2124 2014-05-22 15:50:16      na     na      na 2014-05-22 12:20:03     ss # 5: va1va2 va2 2014-06-16    na       0     0  2124 2014-05-22 14:17:33      na     na      na 2014-05-22 12:20:03     ss 

Comments

Popular posts from this blog

cakephp - simple blog with croogo -

How to group boxplot outliers in gnuplot -

bash - Performing variable substitution in a string -