I want to apply a function to each column in R. Suppose following is the dataframe with (3xn):
df <- data.frame(
h1 = c(1,2,3),
h2 = c(2,3,1),
h3 = c(3,2,1),
h4 = c(1,2,3),
h5 = c(1,2,3)
)
rownames(df) <- c("e1", "e2", "e3")
df
# h1 h2 h3 h4 h5
# e1 1 2 3 1 1
# e2 2 3 2 2 2
# e3 3 1 1 3 3
if we want to check if the first 2 elements suppose (e1==1, e2==2) for each column (h1,h2...). How could we apply the checking function to each column in the data frame?
dput(head(x))ordata.frame(...)) directly.lapply(dataframe, myfunc). akrun's suggestion to usecolSumsis one of the special cases, and is much more efficient in this situation.data.frame), this question is a bit more easily reproducible. I kept the row names solely because you referenced them ase1==1, etc; note that many operations on frames will not preserve row names, including just about everything within thetidyversemeta-package; so while I can see some utility in row names in general (and it can be a polarizing opinion for some), I normally don't use or rely on them.