so as you can see i need to selectively choose some columns with certain values of Factor A and certain values of Factor B and add either 1 or 2 or 3 to certain numbers. here's what i've tried so far:
Code:
for (i in length(datum$FactorA)) {
if (datum$FactorA[i]=="a" & datum$FactorB[i]=="d") {
datum$x[i] <- datum$x[i]+1
}
else {
if (datum$FactorA[i]=="b" & datum$FactorB[i]=="e")
datum$x[i]<- datum$x[i]+2
else {
if(datum$FactorA[i]=="c" & datum$FactorB[i]=="d") {
datum$x[i]<- datum$x[i]+3
}
}
}
}
datum
but as you can see nothing really happens when i run the code. does anyone know why is that? and does anyone know if there's an R package or function that has automated this? i could see this as being something potentially useful and having to go through each possible combination of in the Factor columns seems a llittle bit cumbersome.
Re: (basic) column manipulation in R. help please! :(
Code:
for (i in 1:length(datum$FactorA)) {
if (datum$FactorA[i]=="a" & datum$FactorB[i]=="d") {
datum$x[i] <- datum$x[i]+1
}
else {
if (datum$FactorA[i]=="b" & datum$FactorB[i]=="e")
datum$x[i]<- datum$x[i]+2
else {
if(datum$FactorA[i]=="c" & datum$FactorB[i]=="d") {
datum$x[i]<- datum$x[i]+3
}
}
}
}
datum
for (i in 1:length(datum$FactorA)) gives the requested result.
In your code i only gets 1 value (i.e. 12 of length(datum$FactorA)) if you make it 1:length(datum$FactorA) it lets i run through the values 1 to 12.
Re: (basic) column manipulation in R. help please! :(
No problem!
Below an alternative way without for/if-loops, but I'm not aware of any straightforward functions. This is just a way I would approach is, probably someone else can provide a shorter solution.
Code:
FactorA <- as.factor(c("a","a","a","a","b","b","b","b","c","c","c","c"))
FactorB <- as.factor(c("d","d","e","e","d","d","e","e","d","d","e","e"))
FactorCombi <- paste(FactorA, FactorB, sep='')
#> FactorCombi
# [1] "ad" "ad" "ae" "ae" "bd" "bd" "be" "be" "cd" "cd" "ce" "ce"
refset <- data.frame(matchers = c('ad','be','cd'), vals=1:3)
#data frame containing to be matched values with respective addition values
#> refset
# matchers vals
#1 ad 1
#2 be 2
#3 cd 3
result <- sapply(seq_along(FactorCombi), function(x) x + match(FactorCombi[x],refset$matchers))
#> sapply(seq_along(FactorCombi), function(x) x +
# match(FactorCombi[x],refset$matchers))
#[1] 2 3 NA NA NA NA 9 10 12 13 NA NA
result[is.na(result)] <- which(is.na(result))
#assign index values to NA values for which no match was made
datum <- data.frame(FactorA,FactorB,result)