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
111 views
in Technique[技术] by (71.8m points)

r - Change object names using if()

I am stuck on a question for an assignment for a base R class.

I need to use if() to change the names of several objects. Anything named af, aflb, afub, afwb, or afws will be changed to af_type. They are in the column LANDSCAPE.

Here is the code I have tried:

poppy <- read.csv("~/baseR-V2021.1EXP/data/exercise_dat/bearclawpoppy.csv")

af_type <- if(any(poppy$LANDSCAPE == "af", "aflb", "afub", "afwb", "afws"))"af_type"

af_type <- if(any(poppy$LANDSCAPE == "af", "aflb", "afub", "afwb", "afws")){"af_type"}

When these didn't work, I tried to simplify it:

af_type <- if(poppy$LANDSCAPE == "af")"af_type"

I get an error saying argument is of length zero.

Then I tried:

af_type <- ifelse(poppy$LANDFORM == "af", "af_type", "other")

Return labelled all objects "other".

Here is a screenshot to show what the dataset looks like.

enter image description here

I would appreciate advice! Thank you

question from:https://stackoverflow.com/questions/65912614/change-object-names-using-if

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

1 Reply

0 votes
by (71.8m points)

You're close on the ifelse attempt:

# Create Sample Data (you will read from CSV)
poppy <- data.frame(STUFF = runif(10), 
                 LANDFORM = c("99", "af", "aflb", "98", "afub", "96", 
                              "afwb", "38", "afws", "93"))
poppy
#         STUFF LANDFORM
# 1  0.37938328       99
# 2  0.77255267       af
# 3  0.24627966     aflb
# 4  0.84687320       98
# 5  0.00620105     afub
# 6  0.41519231       96
# 7  0.57605363     afwb
# 8  0.03165768       38
# 9  0.17563387     afws
# 10 0.72591850       93

# Modify Landform column
poppy$LANDFORM <- ifelse(substring(poppy$LANDFORM, 1, 2) == "af", 
                         "af_type", poppy$LANDFORM)

poppy
#          STUFF LANDFORM
# 1  0.946401985       99
# 2  0.257273554  af_type
# 3  0.196977039  af_type
# 4  0.737366269       98
# 5  0.111240430  af_type
# 6  0.099847307       96
# 7  0.423007553  af_type
# 8  0.593641209       38
# 9  0.384637284  af_type
# 10 0.009248734       93

Note that the substring assumes each value in LANDFORM is at least 2 characters, and there are no other strings that start with 'af'. If either is not true, you can do poppy$LANDFORM %in% c("af", "aflb", "afub", "afwb", "afws") instead. Everything else will be the same.


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

...