英文:
How to divide only a certain factor in a column in R data frame?
问题
这是示例数据集:
library(data.table)
df = data.table(x = c(1000,2000,10,2), y = c('A','A','B','B'))
我只想将 df$y == "A"
除以 1000。最终数据集应如下所示:
df = data.table(x = c(1,2,10,2), y = c('A','A','B','B'))
英文:
This is the sample dataset:
library(data.table)
df = data.table(x = c(1000,2000,10,2), y = c('A','A','B','B'))
I only want to divide df$y == "A" by 1000
. The final dataset should appear as:
df = data.table(x = c(1,2,10,2), y = c('A','A','B','B'))
答案1
得分: 3
在基本的R中:
df$x <- ifelse(df$y == "A", df$x/1000, df$x)
在dplyr
中:
library(dplyr)
df <- df %>%
mutate(x = if_else(y == "A", x/1000, x))
英文:
You need to create a conditional statement.
In base R:
df$x <- ifelse(df$y == "A", df$x/1000, df$x)
In dplyr
:
library(dplyr)
df <- df |>
mutate(x = if_else(y == "A", x/1000, x))
答案2
得分: 2
使用 `data.table` 选项,像这样使用 `fifelse`:
``` r
library(data.table)
df = data.table(x = c(1000,2000,10,2), y = c('A','A','B','B'))
df[,x:=fifelse(y == "A", x/1000, x),]
df
#> x y
#> 1: 1 A
#> 2: 2 A
#> 3: 10 B
#> 4: 2 B
2023-02-18 创建,使用 reprex v2.0.2
<details>
<summary>英文:</summary>
`data.table` option using `fifelse` like this:
``` r
library(data.table)
df = data.table(x = c(1000,2000,10,2), y = c('A','A','B','B'))
df[,x:=fifelse(y == "A", x/1000, x),]
df
#> x y
#> 1: 1 A
#> 2: 2 A
#> 3: 10 B
#> 4: 2 B
<sup>Created on 2023-02-18 with reprex v2.0.2</sup>
答案3
得分: 2
我们可以使用 `data.table` 的方法,因为输入是一个 `data.table`。
library(data.table)
df[y == 'A', x := x/1000]
-输出
> df
x y
1: 1 A
2: 2 A
3: 10 B
4: 2 B
<details>
<summary>英文:</summary>
We could use `data.table` methods as the input is a `data.table`
library(data.table)
df[y == 'A', x := x/1000]
-output
> df
x y
1: 1 A
2: 2 A
3: 10 B
4: 2 B
</details>
# 答案4
**得分**: 1
基础R:使用[
进行子集提取:
df$x[df$y == "A"] <- df$x[df$y == "A"]/1000
x y
1: 1 A
2: 2 A
3: 10 B
4: 2 B
英文:
Base R: Subsetting with [
:
df$x[df$y == "A"] <- df$x[df$y == "A"]/1000
x y
1: 1 A
2: 2 A
3: 10 B
4: 2 B
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论