通过创建临时变量来交换两个变量

时间:2018-02-08 00:40:00

标签: r

我是R编程的新手。

我有两个变量:

A <- "Jack,Harris,Nelly"
B <- "Robert,Josh,Mary"

我需要将矢量A的所有三个名称复制到矢量B,将矢量B复制到矢量A(交换)。 我创建了第三个向量

C <- vector(“character”,length=3)

......我被困在那儿了。你能帮我吗?

我非常感谢你的帮助。感谢

2 个答案:

答案 0 :(得分:4)

不是100%肯定你为什么需要交换,但你可以这样做。如果您解释完整的推理,我们可以为您的问题找到更好的解决方案。但这会奏效:

const pie_values = [20,10,5,5,10];

function pied(n) {
  var i = 0;
  var total = pie_values[0];

  while (total < n && i < pie_values.length) {
    i++;
    total += pie_values[i];
  }

  if (i < pie_values.length) {
    var diff = total - n;
    if (diff > 0 && n > 0) { 
      return [].concat(
      	pie_values.slice(0, i), // the part of the array up to i
        pie_values[i] - diff, // the amount we used of the last element we needed
        diff, // the amount left over
        pie_values.slice(i + 1) // the rest of the array after i
      );
    } else {
      // just return a copy of the original array
      return pie_values.slice();
    }
  } else {
    // n was greater than the total of all elements of the array
    return "went over";
  }
}

console.log(pied(5));

答案 1 :(得分:1)

使用list2env稍微不同的版本:

A <- "Jack,Harris,Nelly"
B <- "Robert,Josh,Mary"

list2env(list(A=B,B=A), envir=.GlobalEnv)
#<environment: R_GlobalEnv>

A
#[1] "Robert,Josh,Mary"
B
#[1] "Jack,Harris,Nelly"