Meredith, Christy S -FS
2012-Oct-24 19:56 UTC
[R] randomly select another observation with same grouping factor and year value, do for every record in dataframe
Hello, I am trying to create a function that will move through each record of a data frame, find the value in the "HUC" column, then randomly select another observation from the dataframe with the same value in "HUC" column, as well as the same value in "Yr" column as the first observation. I want the function to produce a list of the RchID of the first observation, the RchID of the second randomly chosen observation, and several other characteristics of the randomly chosen observation. Below is the code I have written, but it doesn't work. Thanks for any help. Christy ################test roads=read.csv("streamland23.csv") for (i in 1:nrow (roads)){ Sitetype= roads$Sitetype yr=roads$REACH_Yr initRchid=roads$RchID huc1=roads$HUC sample.df <- function(df, n) df[sample(nrow(df), n), , drop = FALSE] selected=sample.df(roads[roads$HUC == "huc1"& roads$REACH_Yr =="yr" , ], 1) output=cbind (initRchid,selected$RchID,selected$Sitetype,selected$REACH_Yr) } Christy Meredith USDA Forest Service Rocky Mountain Research Station PIBO Monitoring Data Analyst Voice: 435-755-3573 Fax: 435-755-3563 This electronic message contains information generated by the USDA solely for the intended recipients. Any unauthorized interception of this message or the use or disclosure of the information it contains may violate the law and subject the violator to civil or criminal penalties. If you believe you have received this message in error, please notify the sender and delete the email immediately. [[alternative HTML version deleted]]
csmeredith
2012-Oct-25 14:53 UTC
[R] help appending randomly selected observation based on criteria
Hello, I wrote a request yesterday on how to select a random observation that met certain criteria. I think mostly I have it figured out, but I can't figure out how to append the observations. The output just has one observation in it. Any help would be appreciated, thanks. Christy setwd ("C:/christy/roads/") roads=read.csv("streamland23.csv") for (i in 1:nrow (roads)){ Sitetype= roads$Sitetype[i] yr=roads$REACH_Yr[i] initRchid=roads$RchID[i] huc1=roads$HUC[i] sample.df <- function(df, n) df[sample(nrow(df), n), , drop = FALSE] selected=sample.df(roads[roads$HUC == huc1, ], 1) selectedb=selected selectedb$oldrch=initRchid write.csv(selectedb,file="outhuc3.csv",append=TRUE) } -- View this message in context: http://r.789695.n4.nabble.com/randomly-select-another-observation-with-same-grouping-factor-and-year-value-do-for-every-record-in-e-tp4647351p4647420.html Sent from the R help mailing list archive at Nabble.com.