簡體   English   中英

R:在多個條件下對行進行突變

[英]R: mutate rows on multiple conditions

我是R的新手,遇到了問題。 我想根據它們的值對數字進行突變,並指出它們各自的單位(數字->字符)。 最好按行(而不是按列)進行評估。 這是一個簡單的示例,希望您可以從無法正常使用的功能中了解我的想法。 非常感謝你!

text_tbl <- data.frame(Items = c("Item1", "Item2", "Item3"),
                       Value1 = c(0.9, 11.5, 3000.5),
                       Value2 = c(0.1, 205.5, 1200.5))

transform_scale <- function(x) {
  if(any(x > =1000)) {
    y <- x/1000
    y <- signif(y, digits = 2)
    x <- cat(paste(y, "tn", sep = ""))
  } else if(any(x < 1)) {
    y <- x*1000
    y <- signif(y, digits = 2)
    x <- cat(paste(y, "mn", sep = ""))
  } else {
    x <- signif(x, digits = 2)
    x <- cat(paste(x, "bn", sep = ""))
  }
}

text_tbl[1:3, 2:3] <- apply(text_tbl[1:3, 2:3], 1, transform_scale)

你是這個意思嗎

library(dplyr)

text_tbl %>%
  mutate_at(vars(Value1:Value2), 
            funs(new = case_when(. >= 1000 ~ paste(signif(./1e3, 2), "tn"),
                                 . < 1     ~ paste(signif(.*1e3, 2), "mn"),
                                 TRUE      ~ paste(signif(., 2), "bn"))))

這使

  Items Value1 Value2 Value1_new Value2_new
1 Item1    0.9    0.1     900 mn     100 mn
2 Item2   11.5  205.5      12 bn     210 bn
3 Item3 3000.5 1200.5       3 tn     1.2 tn


樣本數據:

text_tbl <- structure(list(Items = structure(1:3, .Label = c("Item1", "Item2", 
"Item3"), class = "factor"), Value1 = c(0.9, 11.5, 3000.5), Value2 = c(0.1, 
205.5, 1200.5)), .Names = c("Items", "Value1", "Value2"), row.names = c(NA, 
-3L), class = "data.frame")

#  Items Value1 Value2
#1 Item1    0.9    0.1
#2 Item2   11.5  205.5
#3 Item3 3000.5 1200.5

我自己發布的問題的更一般的解決方案:

transform<-function(x){
if(!is.na(x)){
x<-as.numeric(as.character(x))
if(abs(x)<1e6){
x<-as.character(paste(format(round(x/10^3,1),nsmall=1),"th",sep=""))
}else if(abs(x)<1e9&abs(x)>=1e6){
x<-as.character(paste(format(round(x/10^6,1),nsmall=1),"m",sep=""))
}else if(abs(x)<1e12&abs(x)>=1e9){
x<-as.character(paste(format(round(x/10^9,1),nsmall=1),"b",sep=""))
}else if(abs(x)>=1e12){
x<-as.character(paste(format(round(x/10^12,1),nsmall=1),"t",sep=""))
}
}else{
x<-NA
}
}

暫無
暫無

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

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