r - Function for every row in one column in data frame -
how deal for-loops calculating function each row in data frame this:
for (i in 1:nrow(stemmed2)){ stemmed2$stem[i] <- gsub('in ', 'in_', stemmed2$stem[i]) }
i tried this
apply(stemmed2[1], 2, function(x) gsub('in ', 'in_', x))
i believe more efficient way exist (like apply or smth). please, me.
upd. ok, see, thank you! have example:
corr <- function(x){ df <- wd3[wd3$word==as.character(x),] if (nrow(df) < 3) {return('0')} else { cor <- cor.test(df$star, df$count) cor$estimate } }
and
for (i in 1:nrow(wd3)) { wd3$corr[i] <- corr(wd3$word[i]) }
in case
wd3$corr <- corr(wd3$word)
not working...
i think should want:
corr <- function(x){ df <- iris[iris$species == as.character(x), ] if (nrow(df) < 3) { return('0') } else { cor <- cor.test(df$sepal.length, df$sepal.width) cor$estimate } } corr("virginica") corr("setosa") correlation <- sapply(unique(iris$species), corr) # , if want integrate data frame should it: iris$corr <- rep(correlation, each = table(iris$species))
the function returns correlation estimate correctly problem looping through every element of word vector. can replace sapply function using unique elements of word vector. can integrate correlation in data frame repeating correlation estimates many times there words.
Comments
Post a Comment