简体   繁体   English

r的最新版本的位置

[英]Position of the latest version in r

I have 5 variables. 我有5个变量。 I want to Create one variable which has the latest version. 我想创建一个具有最新版本的变量。

For Example. 例如。

Version10 Version 8 Version9 Version 5 version1  expected Output
  1         1          0         0        0      Version10
  0        0            1       1        0       Version9
  0          1         1        1         1      Version8
  0          0          0        0        1       version1      

I tried with following syntax but getting an error. 我尝试使用以下语法,但收到错误。

df<-data.frame(cbind(Version10,Version9,Version8,Version5,Version1)) DF <-data.frame(cbind(Version10,Version9,版本8,版本5,版本1))

for (i in 1:5) {
if (maxvalue==df(I) {
maxvar<-i
maxcount<-maxcount+1 }

Please suggest. 请建议。

Thanks Tanuvi 谢谢Tanuvi

we can use max.col to find the index of the max value in each row, if there are multiple max values, then use the ties.method = "first" . 我们可以使用max.col来查找每行中最大值的索引,如果有多个最大值,则使用ties.method = "first" subset the column names based on the index and create a new column 根据索引对列名称进行子集化并创建新列

df1$expectedOutput <- names(df1)[max.col(df1, "first")]
df1$expectedOutput
#[1] "Version10" "Version9"  "Version8"  "Version1" 

data 数据

df1 <- structure(list(Version10 = c(1L, 0L, 0L, 0L), Version8 = c(1L, 
 0L, 1L, 0L), Version9 = c(0L, 1L, 1L, 0L), Version5 = c(0L, 1L, 
1L, 0L), Version1 = c(0L, 0L, 1L, 1L)), .Names = c("Version10", 
"Version8", "Version9", "Version5", "Version1"), class = "data.frame", 
row.names = c(NA, -4L))

You are missing something in row 3, I guess the expected outcome should be version 9 her instead of v8. 你在第3行遗漏了一些东西,我想预期的结果应该是版本9而不是v8。

Secondly, as you are defining string data frame so use the quotation around versions. 其次,在定义字符串数据框时,请使用版本周围的引号。 Try something this with correct logic. 用正确的逻辑尝试一下这个。

df<data.frame(cbind('Version10','Version9','Version8','Version5','Version1'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM