如何使用嵌套循环?

时间:2019-04-06 07:32:33

标签: r loops

我有一个数据框(称为NP),其中每列(在2到29之间-这些是国家/地区)都有时间序列数据,所以第一列是几年。我想为每一列查找值最接近一组值的年份,然后从中创建一个数据框(或矩阵?)。

以下代码可用于一个单一值(200)。

class CustomUpload extends Component {
  state = { loading: false, imageUrl: '' };
  
  handleChange = (info) => {
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }
    if (info.file.status === 'done') {
      getBase64(info.file.originFileObj, imageUrl => this.setState({
        imageUrl,
        loading: false
      }));
    }
  };

  beforeUpload = (file) => {
    const isImage = file.type.indexOf('image/') === 0;
    if (!isImage) {
      AntMessage.error('You can only upload image file!');
    }
    
    // You can remove this validation if you want
    const isLt5M = file.size / 1024 / 1024 < 5;
    if (!isLt5M) {
      AntMessage.error('Image must smaller than 5MB!');
    }
    return isImage && isLt5M;
  };

  customUpload = ({ onError, onSuccess, file }) => {
    const storage = firebase.storage()
    const metadata = {
        contentType: 'image/jpeg'
    }
    const storageRef = await storage.ref()
    const imageName = generateHashName() //a unique name for the image
    const imgFile = storageRef.child(`Vince Wear/${imageName}.png`)
    try {
      const image = await imgFile.put(file, metadata);
      onSuccess(null, image))
    catch(e) {
      onError(e);
    }
  };
  
  render () {
    const { loading, imageUrl } = this.state;
    const uploadButton = (
    <div>
      <Icon type={loading ? 'loading' : 'plus'} />
      <div className="ant-upload-text">Upload</div>
    </div>
    );
    return (
      <div>
        <Upload
          name="avatar"
          listType="picture-card"
          className="avatar-uploader"
          beforeUpload={this.beforeUpload}
          onChange={this.handleChange}
          customRequest={this.customUpload}
        >
          {imageUrl ? <img src={imageUrl} alt="avatar" /> : uploadButton}
        </Upload>
      </div>
    );
  }
}

我想拥有的不仅仅是一个单一的值200,而是一连串的值(X)。我尝试过:

del <- vector()
for (i in seq_along(NP[,2:29])) {
  del[i] <- which.min(abs(NP[,2:29][[i]] - 200))
}
del
NP$Year[del]
 [1] 1970 1995 1980 1970 1970 1992 1980 1994 1980 1970 1997 1970 1980 1998 1995 1970
[17] 1992 1990 1970 1970 1995 1991 2008 1980 1996 1970 1970 1970

尽管如此,矩阵没有给出正确的值。我究竟做错了什么?谢谢。

这是我的数据框: https://www.dropbox.com/s/4mwi4480ewaahm0/NP.xlsx?dl=0

我希望得到的结果是:一个单独的数据框,其中列将是国家,行将是200到700之间的值,而条目将是年。

2 个答案:

答案 0 :(得分:1)

我认为问题出在i in seq_along(X)上,它在您的情况下会产生一个序列1 2 3 4 5 6 7 8 9 10 11,但是您想在内部循环中减去X的值。您必须将代码调整为

X = seq(from=200, to=700, by=50)
mymatrix <- matrix(nrow = 11, ncol = 28)
for (i in seq_along(X)) {
  for (j in seq_along(NP[,2:29])){
    mymatrix[i,j] <- which.min(abs(NP[,2:29][[j]]) - X[i])
  }
}

答案 1 :(得分:1)

这是带有sapply的较短版本的双循环。我们遍历X的值和NP的所有列,并获得它们之间的绝对值的最小索引。

sapply(X, function(x) sapply(NP[2:29], function(y) which.min(abs(y - x))))


#               [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11]
#Belgium           1    1    2    2    5   12   28   28   28    28    28
#Bulgaria          8   13   16   23   26   28   28   28   28    28    28
#Czech Republic    2    5    8   14   19   26   28   28   28    28    28
#Denmark           1    2    4   15   25   28   28   28   28    28    28
#Germany           1    1    2    2   10   10    9   28   28    28    28
#Estonia           5    7   14   17   20   25   27   28   28    28    28
#Ireland           2    6    9   13   18   21   21   21   21    21    21
#.....

如果您想找出年份

sapply(X, function(x) sapply(NP[2:29], function(y) NP$Year[which.min(abs(y - x))]))


#               [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11]
#Belgium        1970 1970 1980 1980 1992 1999 2015 2015 2015  2015  2015
#Bulgaria       1995 2000 2003 2010 2013 2015 2015 2015 2015  2015  2015
#Czech Republic 1980 1992 1995 2001 2006 2013 2015 2015 2015  2015  2015
#Denmark        1970 1980 1991 2002 2012 2015 2015 2015 2015  2015  2015
#Germany        1970 1970 1980 1980 1997 1997 1996 2015 2015  2015  2015
#Estonia        1992 1994 2001 2004 2007 2012 2014 2015 2015  2015  2015
#Ireland        1980 1993 1996 2000 2005 2008 2008 2008 2008  2008  2008
#......