迭代列名称的子集

时间:2016-10-13 11:37:33

标签: r loops for-loop nested dplyr

我是R的新手但在这里我有一个多个测量条件的数据框,我想在相同条件的列上执行嵌套循环,测试它们是否有两个真实的测量值(非零)至少,如果是这样,计算新数据集中这些特定条件的平均值。

    > sample <- list(c(8,0,12,5,0,11), c(15,5,0,10,12,13), c(1,1,0,3,0,9), 
      c(11,9,8,0,4,7), c(12,5,5,0,9,0), c(1,7,2,0,8,0))
    > sample <- as.data.frame(sample)
    > colnames(sample) <- c("x.1","x.2","x.3","y.1","y.2","y.3")


   > sample
  x.1 x.2 x.3 y.1 y.2 y.3
1   8  15   1  11  12   1
2   0   5   1   9   5   7
3  12   0   0   8   5   2
4   5  10   3   0   0   0
5   0  12   0   4   9   8
6  11  13   9   7   0   0

我的输出数据集理想情况应如下所示:

> Newsample
   x y
1  8 8
2  2 7
3  0 5
4  6 0
5  0 7
6 11 0

2 个答案:

答案 0 :(得分:2)

我们定义f_rowmean函数:

f_rowmean <- function(y) apply(y,1, function(x) ifelse(sum(x!=0)>=2, mean(x), 0))

然后:

data.frame(x=f_rowmean(sample[,grep("x", names(sample))]), 
           y=f_rowmean(sample[,grep("y", names(sample))]))

   # x y
# 1  8 8
# 2  2 7
# 3  0 5
# 4  6 0
# 5  0 7
# 6 11 0

修改

至于OP的新问题陈述(在评论中),假设您的数据集在df1,那么您可以这样做:

res.cols <- c("CAOV-3 Reg", "CAOV-3 Mod", "OVCAR-3Reg", "OVCAR-4Reg", "VOA1056Reg", 
"VOA4698Reg", "VOA4698Mod", "TOV112DReg", "TOV112DMod", "TOV21G Mod", 
"HCC38 Reg", "HCC38 Mod")

res <- setNames(data.frame(matrix(0,nrow(df1),length(res.cols))), res.cols)
res <- sapply(res.cols, function(x) res[,x] <- f_rowmean(df1[,grep(x, names(df1))]))

答案 1 :(得分:0)

我们遍历&#39; x&#39;的索引。并且&#39; y&#39; rowSums中的列,获取逻辑矩阵的ifelse并使用rowMeans获取data.frame(setNames(lapply(list(grep("^x", names(sample)), grep("^y", names(sample))), function(i) { x1 <- sample[i] ifelse(rowSums(x1!=0)>1, rowMeans(x1), 0)}), c("x", "y"))) # x y #1 8 8 #2 2 7 #3 0 5 #4 6 0 #5 0 7 #6 11 0

import android.accounts.Account;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;

import com.google.android.gms.auth.GoogleAuthException;
import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.urbanft.utils.AppToast;

import java.io.IOException;

/**
 * Created by kiwitech on 13/10/16.
 */

public class GoogleLogin extends FragmentActivity implements GoogleApiClient.OnConnectionFailedListener {

    private GoogleSignInOptions gso;
    protected GoogleApiClient mGoogleApiClient;
    private int RC_SIGN_IN = 100;
    public static String GOOGLE_ACCESS_TOKEN = "google_access_token";
    public static String GOOGLE_USER_ID = "google_user_id";
    private String mGooglesUserId;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initialize();
    }

    private void initialize(){
        gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .build();

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this , this)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();
    }

    protected void goForGoogleSignIn(){
        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RC_SIGN_IN) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            if(result.isSuccess()){
                AppToast.showToast(this,"Google sign-in success");
                mGooglesUserId = result.getSignInAccount().getId();
                new LocalAsyncTask(result.getSignInAccount().getEmail()).execute();
            }else{
                AppToast.showToast(this,"Google sign-in failure");
                onBackPressed();
                finish();
            }
        }
    }

    class LocalAsyncTask extends AsyncTask<String,String,String> {

        private String email;

        LocalAsyncTask(String email) {
            this.email = email;
        }

        @Override
        protected String doInBackground(String... params) {
            String token = null;
            try {
                String SCOPE = "oauth2:https://www.googleapis.com/auth/userinfo.profile";
                Account account = new Account(email, "com.google");
                token = GoogleAuthUtil.getToken(GoogleLogin.this, account, SCOPE);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (GoogleAuthException e) {
                e.printStackTrace();
            }
            return token;
        }

        @Override
        protected void onPostExecute(String s){
            Intent intent =new Intent();
            intent.putExtra(GOOGLE_ACCESS_TOKEN,s);
            intent.putExtra(GOOGLE_USER_ID,mGooglesUserId);
            setResult(Activity.RESULT_OK, intent);
            onBackPressed();
            finish();
        }
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    }
}