简体   繁体   中英

applying a formula to every row in a dataframe using a loop/apply/lapply

I have the following dataframe:

0.159774955 0.315950195 1.043728695 -0.013713845    0.300639692 0.089504862
0.225828659 0.359430606 0.837824198 0.023545454 0.454365387 0.146044804
0.200956642 0.284167712 0.741477338 0.095507608 0.380116007 0.108930805
0.178781669 0.268168151 0.890674193 0.025867199 0.439498785 0.090581651
0.259719853 0.253015856 0.733539294 -0.021271503    0.34807779  0.134256761
0.237380703 0.259466053 0.438376163 -0.017622207    0.403244764 0.123988446
0.255139392 0.249787728 0.429777131 0.003033289 0.357595856 0.135647263
0.231928182 0.229371247 0.374830209 0.048649557 0.412691492 0.135958108

I want to apply the following resample code to every row:

replicate(6, mean(sample(one, 6, replace=TRUE)))

at the end I want the answers to be saved in an output dataframe. So basically the task is to run a resample function on every row of a dataframe and to save the output to a new dataframe in the most efficient manner.

Can someone help me in writing a loop for this please

If you want to apply a function to every row of a df you can do the following:

apply(array, margin, fun(x))

where array is your dataframe, margin takes 1 for rows, 2 for columns, fun(x) is your function whee x is each row, eg function(x){mean(x)}


For your function, try

as.data.frame(t(apply(df, 1, function(x){
  replicate(6, mean(sample(x, 6, replace=TRUE)))
})))

where df is your dataframe. Result:

> set.seed(1)
> as.data.frame(t(apply(df, 1, function(x){
+   replicate(6, mean(sample(x, 6, replace=TRUE)))
+ })))
         V1        V2        V3        V4         V5        V6
1 0.3068208 0.1422921 0.5131469 0.3159808 0.61606935 0.4984955
2 0.4083824 0.3365791 0.5149758 0.2826672 0.34761771 0.4413220
3 0.5306285 0.4393809 0.2884135 0.2416325 0.46592721 0.2858680
4 0.4046463 0.3153975 0.5783785 0.1321199 0.06213869 0.1863585
5 0.3461146 0.1959594 0.1886254 0.4904454 0.34373307 0.2179313
6 0.1681255 0.2924128 0.1607637 0.2372478 0.18738553 0.2585522
7 0.2015053 0.1494048 0.2805252 0.3345927 0.22052876 0.2905973
8 0.2724066 0.2384786 0.2612100 0.2544667 0.25447366 0.2393240

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM