如何将数据框中的某些单元格除以 1000

How do I divide certain cells in a dataframe by 1000

如何将列中的某些单元格除以 1000

我想创建一个函数,将 200 的值除以 1000

例如,在第10行第3列(权重)中,有一个值722.666667

我使用了函数

Updins$weight <- as.numeric(Updins$weight)
Updins$body_length <- as.numeric(Updins$body_length)
Updins$tarsus_width <- as.numeric(Updins$tarsus_width) 

对想要的列进行数值化,之前用过这个函数(下)没有成功(我是菜鸟新手,所以好多没看懂!)

library(dplyr) 

test <- Updins %>%
   mutate(weight = ifelse(as.numeric(weight) > 199, 
                          as.character(as.numeric(weight)/1000), weight) 

head(test)

(Updins 是数据框)

有谁知道我做错了什么以及如何让它起作用?

好的,所以我只将一列权重作为数据框中的唯一列,看看它是否回答了您的查询,正如 Rui Barradas 提到的,您不需要 as.numeric()。

> df
# A tibble: 14 x 1
   weight
    <dbl>
 1 109.  
 2  79.4 
 3  23.6 
 4 118.  
 5  89.4 
 6 134.  
 7   4.92
 8 117.  
 9  64.6 
10 723.  
11 107.  
12  18.5 
13  12.0 
14  43.8 
> df$adjusted_weight <- ifelse(df$weight> 199, df$weight/1000, df$weight)
> df
# A tibble: 14 x 2
   weight adjusted_weight
    <dbl>           <dbl>
 1 109.           109.   
 2  79.4           79.4  
 3  23.6           23.6  
 4 118.           118.   
 5  89.4           89.4  
 6 134.           134.   
 7   4.92           4.92 
 8 117.           117.   
 9  64.6           64.6  
10 723.             0.723
11 107.           107.   
12  18.5           18.5  
13  12.0           12.0  
14  43.8           43.8  
> 

或者tidyr方式

library(tidyverse)
updins <- updins %>% mutate(weight = ifelse(weight>200, weight/1000, weight))

data.table 中的一个选项是

library(data.table)
setDT(df)[, adjusted_weight := weight][weight > 200, adjusted_weight := weight/1000]