R:在多种条件下对行进行突变

时间:2018-10-09 09:46:00

标签: r

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

2 个答案:

答案 0 :(得分:0)

你是这个意思吗?

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

答案 1 :(得分:0)

我自己发布的问题的更一般的解决方案:

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