将因子设置为仅一个级别

时间:2018-02-17 20:47:58

标签: r dataframe

我想将因子变量的每个实例设置为常数因子级别,但保留其他级别(不存在)级别的知识。所以:

pp.df<-data.frame(c(1:10))
for (itype in 1:4){
    pp.df$TYPE<-itype
    pp.df$TYPE<-as.factor(pp.df$TYPE)
    levels(pp.df$TYPE)<-c("T","D","F","S")
    print(summary(pp.df$TYPE))
}

产生

 T  D  F  S 
10  0  0  0 
 T  D  F  S 
10  0  0  0 
 T  D  F  S 
10  0  0  0 
 T  D  F  S 
10  0  0  0 

虽然所需的输出是:

 T  D  F  S 
10  0  0  0 
 T  D  F  S 
 0 10  0  0 
 T  D  F  S 
 0  0 10  0 
 T  D  F  S 
 0  0  0 10 

2 个答案:

答案 0 :(得分:1)

这样的事情?

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {


TextView textView;
String googleImageUrl = "https://www.google.co.in/search?biw=1366&bih=675&tbm=isch&sa=1&ei=qFSJWsuTNc-wzwKFrZHoCw&q=";
ArrayList<String> urls = new ArrayList<>();
String url;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    AsyncTask.execute(new Runnable() {
        @Override
        public void run() {
            Log.i("someething" , "something");
            getImages("https://www.google.co.in/search?biw=1366&bih=675&tbm=isch&sa=1&ei=qFSJWsuTNc-wzwKFrZHoCw&q=somethingsomething");
        }
    });
}

private void getImages(String url) {
    Document doc = null;
    try{
        doc = Jsoup.connect(url).get();
    }catch (IOException e){
        e.printStackTrace();
    }
    Elements imgs = doc.select("img");
    System.out.println("Damn images"+imgs);
    for (Element img : imgs){
        Log.d("image-src", img.attr("data-src"));//changed `src` to `data-src`
    }

}

答案 1 :(得分:1)

pp.df<-data.frame(c(1:10))
for (itype in 1:4){
    pp.df$TYPE<-itype

    # need to build the facotr with 4 levels to start with
    pp.df$TYPE<-factor(pp.df$TYPE, levels=1:4)
    levels(pp.df$TYPE)<-c("T","D","F","S")
    print(summary(pp.df$TYPE))
                    }

还应该意识到pp.df在此过程之后不会拥有所有这些值:

> pp.df
   c.1.10. TYPE
1        1    S
2        2    S
3        3    S
4        4    S
5        5    S
6        6    S
7        7    S
8        8    S
9        9    S
10      10    S

如果那是你想要的,那很好。如果没有,你应该描述自然语言需要什么。