我可以循环使用此代码吗?
我只是在学习在R中循环...
event_loggers_es1$main_door_state[event_loggers_es1$main_door_state == "0"] <- "1"
event_loggers_es2$bathroom_door_state[event_loggers_es2$bathroom_door_state == "0"] <- "1"
event_loggers_es3$bedroom_door_state[event_loggers_es3$bedroom_door_state == "0"] <- "1"
event_loggers_es4$bedroom_window_state[event_loggers_es4$bedroom_window_state == "0"] <- "1"
event_loggers_es5$living_door_state[event_loggers_es5$living_door_state == "0"] <- "1"
event_loggers_es6$living_window_state[event_loggers_es6$living_window_state == "0"] <- "1"
event_loggers_es7$balcony_door_state[event_loggers_es7$balcony_door_state == "0"] <- "1"
答案 0 :(得分:0)
我认为以下方法可能有效:
room_types=c('main_door_state','bathroom_door_state',....)
for(i in 1:7){
df=get(paste0('event_loggers_es',i)) #store data of interest in one variable
column_of_interest=df[,colnames(df)==room_types[i]] # specify col
column_of_interest[column_of_interest == "0"] <- "1" #correction
df[,colnames(df)==room_types[i]]=column_of_interest # reassign corrected column to df
assign(paste0('event_loggers_es',i),df) #reassign new df to original 'event_loggers_es*'
}
但是我认为您可以使代码以比当前方式更好的方式遍历数据...例如注释中建议的方式。
或者,如果您的数据集分别位于单独的CSV文件中,则可以通过这种方式进行遍历。
例如:假设您已经将数据保存在单独的CSV文件中(我想您已经拥有了...)-然后您可以执行以下操作:
for(i in 1:7){
df=read.csv(paste0('data_file_',i,'.csv')) #loop through files in directory
#.... then do something with df...
}
我认为以上内容可能比将不同数据帧作为1,2,3 ... 7存储在内存中更好 希望这会有所帮助。