簡體   English   中英

r的最新版本的位置

[英]Position of the latest version in r

我有5個變量。 我想創建一個具有最新版本的變量。

例如。

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      

我嘗試使用以下語法,但收到錯誤。

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

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

請建議。

謝謝Tanuvi

我們可以使用max.col來查找每行中最大值的索引,如果有多個最大值,則使用ties.method = "first" 根據索引對列名稱進行子集化並創建新列

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

數據

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

你在第3行遺漏了一些東西,我想預期的結果應該是版本9而不是v8。

其次,在定義字符串數據框時,請使用版本周圍的引號。 用正確的邏輯嘗試一下這個。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM