将字符的类型转换为数字并保留字符本身是可能的吗?

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

Is it possible to convert the type of a character into numeric while maintaining the character itself?

问题

让我们假设我有这个数据框(df):

df = data.frame(x = c('1E','1E','2F','2F','3F','3E','4E'),
                y = LETTERS[1:7])

第一列(x)的数据类型是字符型。我只想将其数据类型更改为数值型,同时保持相同的变量(也就是说变量 x 仍然包含字母,但其数据类型将变为数值型)。

英文:

let's say I have this df

df = data.frame(x = c('1E','1E','2F','2F','3F','3E','4E'),
                y = LETTERS[1:7] )

The first column (x) is of type character. I just want to change the type to numeric while maintaining the same variable (meaning that the variable x would still have letters. However its type will become numeric).

答案1

得分: 1

我们可以使用

library(dplyr)
df %>%
mutate(x1 = readr::parse_number(x))


-输出

x y x1
1 1E A 1
2 1E B 1
3 2F C 2
4 2F D 2
5 3F E 3
6 3E F 3
7 4E G 4


<details>
<summary>英文:</summary>

We could use

library(dplyr)
df %>%
mutate(x1 = readr::parse_number(x))


-output

x y x1
1 1E A 1
2 1E B 1
3 2F C 2
4 2F D 2
5 3F E 3
6 3E F 3
7 4E G 4


</details>



# 答案2
**得分**: 1

你可能正在寻找一个 `factor`。

(df$x <- as.factor(df$x))
# [1] 1E 1E 2F 2F 3F 3E 4E
# Levels: 1E 2F 3E 3F 4E

其中

mode(df$x)
# [1] "numeric"

<details>
<summary>英文:</summary>

You are probably looking for a `factor`.
    
    (df$x &lt;- as.factor(df$x))
    # [1] 1E 1E 2F 2F 3F 3E 4E
    # Levels: 1E 2F 3E 3F 4E
    
where
    
    mode(df$x)
    # [1] &quot;numeric&quot;



</details>



# 答案3
**得分**: 1

我们可以使用 `str_extract` 和正则表达式 [0-9+]:

```R
library(dplyr)
library(stringr)

df %>%
  mutate(x1 = as.numeric(str_extract(x, '[0-9+]')))

x y x1

1 1E A 1
2 1E B 1
3 2F C 2
4 2F D 2
5 3F E 3
6 3E F 3
7 4E G 4

英文:

We could use str_extract with regex [0-9+]:

library(dplyr)
library(stringr)

df %&gt;% 
  mutate(x1 = as.numeric(str_extract(x, &#39;[0-9+]&#39;))) 


 x     y        x1
  &lt;chr&gt; &lt;chr&gt; &lt;dbl&gt;
1 1E    A         1
2 1E    B         1
3 2F    C         2
4 2F    D         2
5 3F    E         3
6 3E    F         3
7 4E    G         4

答案4

得分: 1

你可能需要创建一个新的ID列,通过唯一值对x进行重新编码。
一个巧妙的方法是将其转换为因子,然后转换为数值。
这将创建一个新的数值ID。

library(dplyr)

df %>%
    mutate(new_id = as.numeric(as.factor(x)),
           .after = x)

这段代码的目的是为数据框df创建一个新列"new_id",通过将列"x"的唯一值编码为数值来实现。

英文:

you may have to create a new ID col, recoding x by unique values.
A hacky way would be to convert to factor, then to numeric.
This would create a new numeric ID.

library(dplyr)

df %&gt;%
    mutate(new_id = as.numeric(as.factor(x)),
           .after = x)

   x new_id y
1 1E      1 A
2 1E      1 B
3 2F      2 C
4 2F      2 D
5 3F      4 E
6 3E      3 F
7 4E      5 G

</details>



huangapple
  • 本文由 发表于 2023年3月7日 00:29:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/75653379.html
匿名

发表评论

匿名网友

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

确定