解决方法
一个data.frame是一个列表,所以沿着
- #include <Rdefines.h>
- SEXP df_fun(SEXP df)
- {
- int i,len = Rf_length(df);
- SEXP result;
- PROTECT(result = NEW_CHARACTER(len));
- for (i = 0; i < len; ++i)
- switch(TYPEOF(VECTOR_ELT(df,i))) {
- case INTSXP:
- SET_STRING_ELT(result,i,mkChar("integer"));
- break;
- case REALSXP:
- SET_STRING_ELT(result,mkChar("numeric"));
- break;
- default:
- SET_STRING_ELT(result,mkChar("other"));
- break;
- };
- UNPROTECT(1);
- return result;
- }
然后在R CMD SHLIB df_fun.c之后
- > dyn.load("df_fun.so")
- > df=data.frame(x=1:5,y=letters[1:5],z=pi,stringsAsFactors=FALSE)
- > .Call("df_fun",df)
- [1] "integer" "other" "numeric"
在Rdefines.h(或其等价功能,如getAttrib)中使用GET_CLASS,GET_ATTR和其他宏来发现有关数据帧的其他信息.请注意,data.frame具有与其结构不同的API.所以例如R函数row.names可以返回与存储在row.names属性中的值不同的东西.我认为大多数.Call函数对原子向量进行操作,保持对R级更复杂的对象的操纵.