我正在使用'pls'包,为此我需要生成一个结构与我习惯的结构略有不同的数据帧。
gasoline2 <- as.data.frame(as.matrix(gasoline))
背景信息 - 将数据加载到R中我倾向于将数据转换为.xls,然后将文件转换为.txt,然后将其加载到R.
加载数据时,它看起来像这样:
rep
如何将汽油2的结构转化为汽油结构?
非常感谢您的帮助!
答案 0 :(得分:2)
您正在寻找list
,这样您就可以将不同的数据结构(例如data.frame
或矩阵)合并为## Assume you are starting with this:
X <- as.data.frame(as.matrix(gasoline))
## Create a new object where column 1 is the same as the first
## column in your existing data frame, and column 2 is a matrix
## of the remaining columns
newGas <- cbind(X[1], NIR = I(as.matrix(X[-1])))
str(gasoline)
# 'data.frame': 60 obs. of 2 variables:
# $ octane: num 85.3 85.2 88.5 83.4 87.9 ...
# $ NIR : AsIs [1:60, 1:401] -0.050193 -0.044227 -0.046867 -0.046705 -0.050859 ...
# ..- attr(*, "dimnames")=List of 2
# .. ..$ : chr "1" "2" "3" "4" ...
# .. ..$ : chr "900 nm" "902 nm" "904 nm" "906 nm" ...
str(newGas)
# 'data.frame': 60 obs. of 2 variables:
# $ octane: num 85.3 85.2 88.5 83.4 87.9 ...
# $ NIR : AsIs [1:60, 1:401] -0.050193 -0.044227 -0.046867 -0.046705 -0.050859 ...
# ..- attr(*, "dimnames")=List of 2
# .. ..$ : chr "1" "2" "3" "4" ...
# .. ..$ : chr "NIR.900 nm" "NIR.902 nm" "NIR.904 nm" "NIR.906 nm" ...
中的列:
> colnames(newGas$NIR) <- gsub("NIR.", "", colnames(newGas$NIR))
> identical(gasoline, newGas)
[1] TRUE
列命名略有不同,但我认为可以很容易地处理......
#include <iostream>
#include <map>
#include <algorithm>
template<typename K, typename V>
void write_map(const std::multimap<K, V> mm)
{
std::cout << "MultiMap content:"<< std::endl << std::endl;
for(auto it = mm.begin(); it != mm.end(); it++)
std::cout << it->first << "\t" << it->second << std::endl;
}
template<typename K, typename V>
void write_map(const std::map<K, V> m)
{
std::cout << "Map content:"<< std::endl << std::endl;
for(auto it = m.begin(); it != m.end(); it++)
std::cout << it->first << "\t" << it->second << std::endl;
}
template<typename KV, typename VK>
std::pair<VK, KV> flip_pair(const std::pair<KV, VK> &p)
{
return std::pair<VK, KV>(p.second, p.first);
}
template<typename KV, typename VK>
std::multimap<VK, KV> flip_map(const std::map<KV, VK> &src)
{
std::multimap<VK, KV> dst;
// LINE_B follows
std::transform(src.begin(), src.end(), std::inserter(dst, dst.begin()), flip_pair<KV, VK>);
return dst;
}
int main(void)
{
std::map<std::string, uint32_t> m_words_map1;
std::pair<std::string, uint32_t> p1("aaa", 2);
std::pair<std::string, uint32_t> p2("bbb", 1);
m_words_map1.insert(p1);
m_words_map1.insert(p2);
write_map(m_words_map1);
// LINE_A follows
std::multimap<uint32_t, std::string> sorted_multimap1 = flip_map(m_words_map1);
write_map(sorted_multimap1);
}