将变量添加到包含每行最大值的数据框中 [英] Add a variable to a data frame containing max value of each row

查看:46
本文介绍了将变量添加到包含每行最大值的数据框中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向数据框 (df) 添加一个变量(列),在每一行中包含该行第 2 到 26 列的最大值.

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.

对于第一行,代码为:

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

我正在寻找一种方法来概括第 1 到 865 行.如果我给出:

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])

我得到了变量 df$max 的所有行的总体最大值.

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

推荐答案

您可以使用 apply.例如:

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

这是一个基本示例:

> 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

这篇关于将变量添加到包含每行最大值的数据框中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆