Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

r - Why does the sub(...) function completely distort my data frame?

strangely, I didn't come upon this while browsing online. Basically I am trying to apply the sub(...) function to a simple data frame. Please refer to the following example:

x <- data.frame(name=c("Hans", "Dieter", "Peter"), age=c(25,26,27))
data <- data.frame(sub("e", "a", x)) #subbing an e for an a

The output changes the data frame completely, the first row now contains:

c("Hans", "Diater", "Peter")

The second:

c(25, 26, 27)

Might anybody be so kind and help me out so that I can understand what is going on? Many thanks!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The sub() function is not designed to act on whole dataframes, just on individual vectors.

This should work:

x <- data.frame(name=c("Hans", "Dieter", "Peter"), age=c(25,26,27))
x
#>     name age
#> 1   Hans  25
#> 2 Dieter  26
#> 3  Peter  27

library(tidyverse)
data <- x %>% mutate(name = str_replace(name, "e", "a")) #subbing an e for an a
data
#>     name age
#> 1   Hans  25
#> 2 Diater  26
#> 3  Pater  27

or a little shorter without the pipes

data <- mutate(x, name = str_replace(name, "e", "a"))

Created on 2021-01-05 by the reprex package (v0.3.0)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...