有一个R函数可以根据以下条件对数据框进行变换并创建一个新的数据框吗?

huangapple go评论54阅读模式
英文:

Is there an R function to mutate a dataframe and create a new dataframe based on the following conditions?

问题

我有一个类似以下的数据框:

   1.   2.   3.   4.    5. 
R1 NA  881.  NA  NA   NA
R2 650 NA   NA  NA   NA
R3 743 NA   NA  NA   NA

dput

structure(list(V1 = c(NA, 650L, 743L), V2 = c(881L, NA, NA), V3 = c(NA, NA, NA), V4 = c(NA, NA, NA), V5 = c(NA, NA, NA)), row.names = c(NA, -3L), class = "data.frame")
英文:

I have a dataframe similar to the following:

   1.   2.   3.   4.    5. 
R1 NA  881.  950  981.  1000
R2 650 760.  890. NA.   NA
R3 743 834.  960. 1001. 1115

I want to mutate the dataframe and create a new dataframe that keeps only the minimum value of each row, all my unwanted values would return as NA, for an output of something like this:

   1.   2.   3.   4.    5. 
R1 NA  881   NA   NA    NA
R2 650  NA   NA   NA    NA
R3 743  NA   NA   NA    NA

dput:

structure(list(V1 = c(NA, 650L, 743L), V2 = c(881L, 760L, 834L
), V3 = c(950L, 890L, 960L), V4 = c(981L, NA, 1001L), V5 = c(1000L, 
NA, 1115L)), row.names = c(NA, -3L), class = "data.frame")

答案1

得分: 1

在基础R中的解决方案:

t(apply(your_data, 1, \(v) { is.na(v) <- -which.min(v); return(v) }))

这使用了is.na<-赋值,根据索引设置NA值。-which.max(v) 除了第一个最小值之外的所有值。

结果:

           V1  V2 V3 V4 V5
     [1,]  NA 881 NA NA NA
     [2,] 650  NA NA NA NA
     [3,] 743  NA NA NA NA
英文:

A solution in base R:

t(apply(your_data, 1, \(v) { is.na(v) <- -which.min(v); return(v) }))

This uses the is.na<- assigment, which sets NA values based on index. -which.max(v) everthing except the first minimum value.

Gives:

> V1 V2 V3 V4 V5
> [1,] NA 881 NA NA NA
> [2,] 650 NA NA NA NA
> [3,] 743 NA NA NA NA

答案2

得分: 1

df* NA^(col(df) != max.col(-replace(df, is.na(df), Inf)))

X1 NA 881 NA NA NA
X2 650 NA NA NA NA
X3 743 NA NA NA NA

t(apply(df, 1, (x) ifelse(x == min(x, na.rm = TRUE), x, NA)))
X1 NA 881 NA NA NA
X2 650 NA NA NA NA
X3 743 NA NA NA NA

英文:
df* NA^(col(df) != max.col(-replace(df, is.na(df), Inf)))

    X1  X2 X3 X4 X5
R1  NA 881 NA NA NA
R2 650  NA NA NA NA
R3 743  NA NA NA NA

t(apply(df, 1, \(x) ifelse(x == min(x, na.rm = TRUE), x, NA)))
    X1  X2 X3 X4 X5
R1  NA 881 NA NA NA
R2 650  NA NA NA NA
R3 743  NA NA NA NA

huangapple
  • 本文由 发表于 2023年6月2日 02:04:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76384568.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定