All Questions

839
votes
9answers
328381 views

Grouping functions (tapply, by, aggregate) and the *apply family

Whenever I want to do something "map"py in R, I usually try to use a function in the apply family. However, I've never quite understood the differences between them -- how {sapply, lapply, etc.} app...
85
votes
6answers
146795 views

Apply a function to every row of a matrix or a data frame

Suppose I have a n by 2 matrix and a function that takes a 2-vector as one of its arguments. I would like to apply the function to each row of the matrix and get a n-vector. How to do this in R? For ...
15
votes
3answers
23095 views

Concatenate row-wise across specific columns of dataframe

I have a data frame with columns that, when concatenated (row-wise) as a string, would allow me to partition the data frame into a desired form. > str(data) 'data.frame': 680420 obs. of 10 vari...
5
votes
3answers
2732 views

Create frequency tables for multiple factor columns in R

I am a novice in R. I am compiling a separate manual on the syntax for the common functions/features for my work. My sample dataframe as follows: x.sample <- structure(list(Q9_A = structure(c(5L, ...
4
votes
2answers
6238 views

weighted means by group and column

I wish to obtain weighted means by group for each of several (actually about 60) columns. This question is very similar to: repeatedly applying ave for computing group means in a data frame just aske...
7
votes
2answers
9984 views

How do I count the number of words in a text (string)?

I have this string vector (for example): str <- c("this is a string current trey", "feather rtttt", "tusla", "laq") To count the number of words in this vector I used this (as given ...
18
votes
3answers
5918 views

Using "..." and "replicate"

In the documentation of sapply and replicate there is a warning regarding using ... Now, I can accept it as such, but would like to understand what is behind it. So I've created this little contrived...
26
votes
5answers
52167 views

How to subset from a list in R

I have a rather simple task but haven't find a good solution. > mylist [[1]] [1] 1 2 3 4 5 6 7 8 9 10 [[2]] [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r...
5
votes
4answers
4380 views

Extracting nth element from a nested list following strsplit - R

I've been trying to understand how to deal with the output of strsplit a bit better. I often have data such as this that I wish to split: mydata <- c("144/4/5", "154/2", "146/3/5", "142", "143/4...
7
votes
1answers
204 views

Speeding up function that uses which within a sapply call in R

I have two vector e and g. I want to know for each element in e the percentage of elements in g that are smaller. One way to implement this in R is: set.seed(21) e <- rnorm(1e4) g <- rnorm(1e4)...

Previous Next