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

r - assign value to a variable rather than using if statement

Right now, I have dataset consisting of variables Gbcode and ncnty

> str(dt)
'data.frame':   840 obs. of  8 variables:
 $ Gbcode                     : Factor w/ 28 levels "11","12","13",..: 21 22 23 24 25 26 27 28 16 17 ...
 $ ncounty                    : num  0 0 0 0 0 0 0 0 0 0 ...

I want to do the following thing:

if a data record is with Gbcode equal to 11, then assign 20 to its ncnty

Gbcode : 11, 12, 13, 14, 15, 21, 22, 23, 31, 32, 33
Corresponding ncnty: 20, 19, 198, 131, 112, 102, 60, 145, 22, 115, 95

I am wondering whether there is any better solution rather than write an if statement, which would be with many lines in this case, maybe less than 20 lines of code.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

This is a merge operation as far as I can tell. Make a little lookup table with your Gbcode/ncnty data, and then merge it in.

# lookup table
lkup <- data.frame(Gbcode=c(11,12,13),ncnty=c(20,19,198))

#example data
dt <- data.frame(Gbcode=c(11,13,12,11,13,12,12))
dt
#  Gbcode
#1     11
#2     13
#3     12
#4     11
#5     13
#6     12
#7     12

Merge:

merge(dt, lkup, by="Gbcode", all.x=TRUE)
#  Gbcode ncnty
#1     11    20
#2     11    20
#3     12    19
#4     12    19
#5     12    19
#6     13   198
#7     13   198

It is sometimes preferable to use match for this sort of thing too:

dt$ncnty <- lkup$ncnty[match(dt$Gbcode,lkup$Gbcode)]

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

...