获取数据帧中的最小行 [英] Getting the minimum of the rows in a data frame

查看:123
本文介绍了获取数据帧中的最小行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个有65个变量的数据框。第一个变量指定一个人,而接下来的64个变量表示该人来自64个位置的每个地理距离。使用R,我想创建一个新变量,将每个人的最短距离目录到这64个位置之一。



例如:如果人物X距离位置是35,50,79,100,450 ...英里,我希望新变量自动分配一个35,因为这是最短的距离。
对此的任何帮助将不胜感激。谢谢。

解决方案

  df<  -  data.frame(let = letters [1:25] ,d1 =样本(1:25,25),d2 =样本(1:25,25),d3 =样本(1:25,25))

df $最短< df [,2:4],1,min)

第二行将函数min应用于每个行,并将其分配给我的data.frame df中的新列。请参阅?申请以获得更多关于第二行的作用的解释。小心跳过第一列或任何不是距离的列:



apply(df,1,min)给出完全不同的答案,因为它找到字符串的最小。

 > min(2:10)
[1] 2
> min(as.character(2:10))
[1]10


I am working with a dataframe that has 65 variables in it. The first variable catalogs a person, and the next 64 variables indicate the geographic distance that person is from each of 64 locations. Using R, I would like to create a new variable that catalogs the shortest distance for each person to one of those 64 locations.

For example: if person X is 35, 50, 79, 100, 450...miles away from the locations, I would like the new variable to automatically assign them a 35, because this is the shortest distance. Any help with this would be much appreciated. Thanks.

解决方案

df <- data.frame(let=letters[1:25], d1=sample(1:25,25), d2=sample(1:25,25), d3=sample(1:25,25))

df$shortest <- apply(df[,2:4],1,min)

The second line applies the function min to each row and assigns it to the new column in my data.frame df. See ?apply for more explanation of what the second line is doing. Careful to skip the first column, or any columns that aren't distances:

apply(df,1,min) gives completely difference answers since its finding the "min" of strings.

> min(2:10)
[1] 2
> min(as.character(2:10))
[1] "10"

这篇关于获取数据帧中的最小行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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