Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

r - Add a variable to a data frame containing max value of each row

I want to add a variable (column) to a dataframe (df), containing in each row the maximum value of that row across 2nd to 26th column.

For the first row, the code would be:

df$max[1] <- max(df[1,2:26])

I am looking for a way to generalize that for rows 1 to 865. If I give:

df$max[1:865] <- max(df[1:865, 2:26])

I get the overall max across all rows for the variable df$max.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use apply. For instance:

df[, "max"] <- apply(df[, 2:26], 1, max)

Here's a basic example:

> df <- data.frame(a=1:50, b=rnorm(50), c=rpois(50, 10))
> df$max <- apply(df, 1, max)
> head(df, 2)
  a          b  c max
1 1  1.3527115  9   9
2 2 -0.6469987 20  20
> tail(df, 2)
    a          b  c max
49 49 -1.4796887 10  49
50 50  0.1600679 13  50

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...